42 lines
1.2 KiB
Java
Raw Normal View History

2015-12-15 11:47:04 -08:00
// collectionsindepth/SortedMapDemo.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 TreeMap.
import java.util.*;
import onjava.*;
2015-06-15 17:47:35 -07:00
public class SortedMapDemo {
public static void main(String[] args) {
TreeMap<Integer,String> sortedMap =
new TreeMap<>(new CountingMapData(10));
2015-11-03 12:00:44 -08:00
System.out.println(sortedMap);
2015-06-15 17:47:35 -07:00
Integer low = sortedMap.firstKey();
Integer high = sortedMap.lastKey();
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<Integer> it = sortedMap.keySet().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(sortedMap.subMap(low, high));
System.out.println(sortedMap.headMap(high));
System.out.println(sortedMap.tailMap(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
{0=A0, 1=B0, 2=C0, 3=D0, 4=E0, 5=F0, 6=G0, 7=H0, 8=I0,
9=J0}
0
9
3
7
{3=D0, 4=E0, 5=F0, 6=G0}
{0=A0, 1=B0, 2=C0, 3=D0, 4=E0, 5=F0, 6=G0}
{3=D0, 4=E0, 5=F0, 6=G0, 7=H0, 8=I0, 9=J0}
2015-09-07 11:44:36 -06:00
*/