42 lines
1.2 KiB
Java
Raw Normal View History

2015-12-15 11:47:04 -08:00
// collectionsindepth/SortedSetDemo.java
// (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.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// What you can do with a TreeSet.
import java.util.*;
public class SortedSetDemo {
public static void main(String[] args) {
SortedSet<String> sortedSet = new TreeSet<>();
Collections.addAll(sortedSet,
"one two three four five six seven eight"
.split(" "));
2015-11-03 12:00:44 -08:00
System.out.println(sortedSet);
2015-06-15 17:47:35 -07:00
String low = sortedSet.first();
String high = sortedSet.last();
2015-11-03 12:00:44 -08:00
System.out.println(low);
System.out.println(high);
2015-06-15 17:47:35 -07:00
Iterator<String> it = sortedSet.iterator();
for(int i = 0; i <= 6; i++) {
if(i == 3) low = it.next();
if(i == 6) high = it.next();
else it.next();
}
2015-11-03 12:00:44 -08:00
System.out.println(low);
System.out.println(high);
System.out.println(sortedSet.subSet(low, high));
System.out.println(sortedSet.headSet(high));
System.out.println(sortedSet.tailSet(low));
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
[eight, five, four, one, seven, six, three, two]
eight
two
one
two
[one, seven, six, three]
[eight, five, four, one, seven, six, three]
[one, seven, six, three, two]
2015-09-07 11:44:36 -06:00
*/