集合的一个很重要的操作---遍历,学习了三种遍历方法,三种方法各有优缺点~~
01 |
<b> package com.myTest.MapText; |
02 |
03 |
import java.util.Collection; |
04 |
import java.util.HashMap; |
05 |
import java.util.Iterator; |
06 |
import java.util.Map; |
07 |
import java.util.Set; |
08 |
09 |
public class TestMap |
10 |
{ |
11 |
12 |
//1.
最常规的一种遍历方法,最常规就是最常用的,虽然不复杂,但很重要,这是我们最熟悉的,就不多说了!! |
13 |
public static void work(Map<String,
Student> map) |
14 |
{ |
15 |
Collection<Student>
c = map.values(); |
16 |
Iterator<Student>
it = c.iterator(); |
17 |
for (;
it.hasNext();) |
18 |
{ |
19 |
System.out.println(it.next()); |
20 |
} |
21 |
//
当for循环只有一个判断语句的时候,就等同于while循环了 |
22 |
//
while(it.hasNext()) |
23 |
//
{ |
24 |
//
System.out.println(it.next()); |
25 |
//
} |
26 |
|
27 |
} |
28 |
29 |
//
2.利用keyset进行遍历,它的优点在于可以根据你所想要的key值得到你想要的 values,更具灵活性!! |
30 |
public static void workByKeySet(Map<String,
Student> map) |
31 |
{ |
32 |
Set<String>
key = map.keySet(); |
33 |
Iterator<String>
it = key.iterator(); |
34 |
for (;
it.hasNext();) |
35 |
{ |
36 |
String
s = (String) it.next(); |
37 |
System.out.println(map.get(s)); |
38 |
} |
39 |
|
40 |
//用增强型for循环也可 |
41 |
//
for(Object o : map.keySet()) |
42 |
//
{ |
43 |
//
System.out.println(map.get(o)); |
44 |
//
} |
45 |
|
46 |
} |
47 |
48 |
//
3.比较复杂的一种遍历在这里,呵呵~~他很暴力哦,它的灵活性太强了,想得到什么就能得到什么~ |
49 |
public static void workByEntry(Map<String,
Student> map) |
50 |
{ |
51 |
Set<Map.Entry<String,
Student>> set = map.entrySet(); |
52 |
Iterator<Map.Entry<String,
Student>> it = set.iterator(); |
53 |
for (;
it.hasNext();) |
54 |
{ |
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()); |
58 |
} |
59 |
60 |
} |
61 |
62 |
public static void main(String[]
args) |
63 |
{ |
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 ); |
68 |
69 |
map.put( "1001" ,
s1); |
70 |
map.put( "1002" ,
s2); |
71 |
map.put( "1003" ,
s3); |
72 |
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 )); |
76 |
map.putAll(subMap); |
77 |
78 |
//
work(map); |
79 |
workByKeySet(map); |
80 |
//
workByEntry(map); |
81 |
} |
82 |
83 |
}
</b> |
01 |
<b> package com.myTest.MapText; |
02 |
03 |
public class Student |
04 |
{ |
05 |
private String
name; |
06 |
private String
id; |
07 |
private int age; |
08 |
09 |
public Student(String
name, String id, int age) |
10 |
{ |
11 |
this .name
= name; |
12 |
this .id
= id; |
13 |
this .age
= age; |
14 |
} |
15 |
16 |
@Override public String
toString() |
17 |
{ |
18 |
return "Student{" + "name=" +
name + "
id=" +
id + "
age=" +
age + '}' ; |
19 |
} |
20 |
}
</b> |
可直接复制代码到Myeclipse工具中运行看结果。