Step By Step(Java 集合篇) (八)

2014-11-24 03:19:39 · 作者: · 浏览: 19
("IBM", "White Plains, NY");

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 it = sortedMap.keySet().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 map = new LinkedHashMap();

3 map.put("1", "value1");

4 map.put("2", "value2");

5 map.put("3", "value3");

6 map.put("2", "value4");

7 for (Iterator it = map.keySet().iterator(); it.hasNext();) {

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 yourMap = new HashMap();

21 yourMap.put("1", "one");

22 yourMap.put("2", "two");

23 yourMap.put("3", "three");

24

25 Map map = new LinkedHashMap();

26 List keyList = new ArrayList(yourMap.keySet());

27 List valueList = new ArrayList(yourMap.values());

28 Set sortedSet = new TreeSet(valueList);

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 ref = map.keySet();

36 Iterator it = ref.iterator();

37 while (it.hasNext()) {

38 String i = (String) it.next();

39 System.out.println(i);

40 }

41 }

12. EnumSet和EnumMap,这两个集合可以看做是类型参数特化后的Set>和Map,V>,EnumSet没有显示的构造函数,而是通过一组工厂方法来创建了,见如下代码:

1 enum Weekdays {

2 Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday

3 }

4 public static void main(String[] a) {

5 EnumSet es1 = EnumSet.allOf(Weekdays.class);

6 EnumSet es2 = EnumSet.noneOf(Weekdays.class);

7 EnumSet es3 = EnumSet.range(Weekdays.Thursday, Weekdays.Sunday);

8 EnumSet es4 = EnumSet.of(Weekdays.Monday,Weekdays.