2016-08-02 11:52:46 -06:00
|
|
|
// understandingcollections/ListSortSearch.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// Sorting and searching Lists with Collections utilities
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
public class ListSortSearch {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
List<String> list =
|
|
|
|
new ArrayList<>(Utilities.list);
|
|
|
|
list.addAll(Utilities.list);
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(list);
|
2015-06-15 17:47:35 -07:00
|
|
|
Collections.shuffle(list, new Random(47));
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("Shuffled: " + list);
|
2015-06-15 17:47:35 -07:00
|
|
|
// Use a ListIterator to trim off the last elements:
|
|
|
|
ListIterator<String> it = list.listIterator(10);
|
|
|
|
while(it.hasNext()) {
|
|
|
|
it.next();
|
|
|
|
it.remove();
|
|
|
|
}
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("Trimmed: " + list);
|
2015-06-15 17:47:35 -07:00
|
|
|
Collections.sort(list);
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("Sorted: " + list);
|
2015-06-15 17:47:35 -07:00
|
|
|
String key = list.get(7);
|
|
|
|
int index = Collections.binarySearch(list, key);
|
2015-12-02 09:20:27 -08:00
|
|
|
System.out.println(
|
|
|
|
"Location of " + key + " is " + index +
|
2015-06-15 17:47:35 -07:00
|
|
|
", list.get(" + index + ") = " + list.get(index));
|
|
|
|
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
|
2016-01-25 18:05:55 -08:00
|
|
|
System.out.println(
|
|
|
|
"Case-insensitive sorted: " + list);
|
2015-06-15 17:47:35 -07:00
|
|
|
key = list.get(7);
|
|
|
|
index = Collections.binarySearch(list, key,
|
|
|
|
String.CASE_INSENSITIVE_ORDER);
|
2015-12-02 09:20:27 -08:00
|
|
|
System.out.println(
|
|
|
|
"Location of " + key + " is " + index +
|
2015-06-15 17:47:35 -07:00
|
|
|
", list.get(" + index + ") = " + list.get(index));
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
[one, Two, three, Four, five, six, one, one, Two, three,
|
|
|
|
Four, five, six, one]
|
|
|
|
Shuffled: [Four, five, one, one, Two, six, six, three,
|
|
|
|
three, five, Four, Two, one, one]
|
|
|
|
Trimmed: [Four, five, one, one, Two, six, six, three,
|
|
|
|
three, five]
|
|
|
|
Sorted: [Four, Two, five, five, one, one, six, six, three,
|
|
|
|
three]
|
|
|
|
Location of six is 7, list.get(7) = six
|
|
|
|
Case-insensitive sorted: [five, five, Four, one, one, six,
|
|
|
|
six, three, three, Two]
|
|
|
|
Location of three is 7, list.get(7) = three
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|