OnJava8-Examples/collectiontopics/ListSortSearch.java

58 lines
1.9 KiB
Java
Raw Permalink Normal View History

2016-12-30 22:22:39 -08:00
// collectiontopics/ListSortSearch.java
// (c)2021 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.
// Sorting/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);
ListIterator<String> it =
list.listIterator(10); // [1]
while(it.hasNext()) { // [2]
2015-06-15 17:47:35 -07:00
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 +
2017-01-22 16:48:11 -08: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 +
2017-01-22 16:48:11 -08:00
", list.get(" + index + ") = " +
list.get(index));
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
[one, Two, three, Four, five, six, one, one, Two,
three, Four, five, six, one]
2015-06-15 17:47:35 -07:00
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]
2015-06-15 17:47:35 -07:00
Location of six is 7, list.get(7) = six
Case-insensitive sorted: [five, five, Four, one, one,
six, six, three, three, Two]
2015-06-15 17:47:35 -07:00
Location of three is 7, list.get(7) = three
2015-09-07 11:44:36 -06:00
*/