5 sortedMap.put("Learning Tree", "Los Angeles, CA");
6 sortedMap.put("Microsoft", "Redmond, WA");
7 sortedMap.put("Netscape", "Mountain View, CA");
8 sortedMap.put("O'Reilly", "Sebastopol, CA");
9 sortedMap.put("Sun", "Mountain View, CA");
10 System.out.println(sortedMap);
11 //firstKey and lastKey 是SortedMap中提供的方法,HashMap中没有。
12 String low = sortedMap.firstKey(), high = sortedMap.lastKey();
13 System.out.println(low);
14 System.out.println(high);
15 Iterator
16 int i = 0;
17 while (it.hasNext()) {
18 if (i == 3)
19 low = it.next();
20 if (i == 6)
21 high = it.next();
22 else
23 it.next();
24 i++;
25 }
26 System.out.println(low);
27 System.out.println(high);
28 //以下3个方法也是SortedMap中提供的方法,HashMap中没有。
29 System.out.println(sortedMap.subMap(low, high));
30 System.out.println(sortedMap.headMap(high));
31 System.out.println(sortedMap.tailMap(low));
32 }
11. LinkedHashSet和LinkedHashMap:这两个集合与HashSet和HashMap唯一的差异是LinkedHashSet和LinkedHashMap通过内部实现的双向链表保留了集合元素的插入顺序,见如下代码:
1 public static void main(String[] a) {
2 Map
3 map.put("1", "value1");
4 map.put("2", "value2");
5 map.put("3", "value3");
6 map.put("2", "value4");
7 for (Iterator
8 String key = it.next();
9 String value = map.get(key);
10 System.out.println(value);
11 }
12 }
13 /* 结果如下:
14 value1
15 value4
16 value3 */
17
18 //基于Values的排序后输出Keys
19 public static void main(String[] a) {
20 Map
21 yourMap.put("1", "one");
22 yourMap.put("2", "two");
23 yourMap.put("3", "three");
24
25 Map
26 List
27 List
28 Set
29 String[] sortedArray = sortedSet.toArray(new String[0]);
30 int size = sortedArray.length;
31
32 for (int i = 0; i < size; i++)
33 map.put(keyList.get(valueList.indexOf(sortedArray[i])), sortedArray[i]);
34
35 Set
36 Iterator
37 while (it.hasNext()) {
38 String i = (String) it.next();
39 System.out.println(i);
40 }
41 }
12. EnumSet和EnumMap,这两个集合可以看做是类型参数特化后的Set
1 enum Weekdays {
2 Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
3 }
4 public static void main(String[] a) {
5 EnumSet
6 EnumSet
7 EnumSet
8 EnumSet