java遍历Map

No.1 使用 Map.Entry
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.HashMap;
import java.util.Map;

public class TestMap01 {
public static void main(String[] args) {

Map<String, Object> map = new HashMap<String, Object>();
map.put("zhangsan", 20);
map.put("lisi", 50);

for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + "\t" + entry.getKey());
}

}
}
No.2 使用 forEach
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.HashMap;
import java.util.Map;

public class TestMap02 {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("zhangsan", 20);
map.put("lisi", 50);
map.forEach((k, v) -> {
System.out.println(k + "\t" + v);
});
}
}

No.3 使用迭代器(Iterator)遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class TestMap03 {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("zhangsan", 20);
map.put("lisi", 50);
Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, Object> entry = entries.next();
System.out.println(entry.getKey() + "\t" + entry.getValue());
}
}
}