集合的一个很重要的操作---遍历,学习了三种遍历方法,三种方法各有优缺点~~
01 | <b> package com.myTest.MapText; |
03 | import java.util.Collection; |
04 | import java.util.HashMap; |
05 | import java.util.Iterator; |
12 | //1. 最常规的一种遍历方法,最常规就是最常用的,虽然不复杂,但很重要,这是我们最熟悉的,就不多说了!! |
13 | public static void work(Map<String, Student> map) |
15 | Collection<Student> c = map.values(); |
16 | Iterator<Student> it = c.iterator(); |
19 | System.out.println(it.next()); |
21 | // 当for循环只有一个判断语句的时候,就等同于while循环了 |
22 | // while(it.hasNext()) |
24 | // System.out.println(it.next()); |
29 | // 2.利用keyset进行遍历,它的优点在于可以根据你所想要的key值得到你想要的 values,更具灵活性!! |
30 | public static void workByKeySet(Map<String, Student> map) |
32 | Set<String> key = map.keySet(); |
33 | Iterator<String> it = key.iterator(); |
36 | String s = (String) it.next(); |
37 | System.out.println(map.get(s)); |
41 | // for(Object o : map.keySet()) |
43 | // System.out.println(map.get(o)); |
48 | // 3.比较复杂的一种遍历在这里,呵呵~~他很暴力哦,它的灵活性太强了,想得到什么就能得到什么~ |
49 | public static void workByEntry(Map<String, Student> map) |
51 | Set<Map.Entry<String, Student>> set = map.entrySet(); |
52 | Iterator<Map.Entry<String, Student>> it = set.iterator(); |
55 | Map.Entry<String, Student> entry = (Map.Entry<String, Student>) it.next(); |
56 | // System.out.println(entry.getKey() + "--->" + entry.getValue()); |
57 | System.out.println(entry.getValue()); |
62 | public static void main(String[] args) |
64 | Map<String, Student> map = new HashMap<String, Student>(); |
65 | Student s1 = new Student( "宋江" , "1001" , 38 ); |
66 | Student s2 = new Student( "卢俊义" , "1002" , 35 ); |
67 | Student s3 = new Student( "吴用" , "1003" , 34 ); |
73 | Map<String, Student> subMap = new HashMap<String, Student>(); |
74 | subMap.put( "1008" , new Student( "tom" , "1008" , 12 )); |
75 | subMap.put( "1009" , new Student( "jerry" , "1009" , 10 )); |
01 | <b> package com.myTest.MapText; |
09 | public Student(String name, String id, int age) |
16 | @Override public String toString() |
18 | return "Student{" + "name=" + name + " id=" + id + " age=" + age + '}' ; |
可直接复制代码到Myeclipse工具中运行看结果。