如果你现在正在使用Java8,那一定要看看在Java8中,对map操作遍历可以采用第4种方式哦。
一,通过forEach循环遍历
public void test1() throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "a");
map.put(3, "c");
map.put(4, "d");
map.put(2, "b");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + " Value = "+ entry.getValue());
}
}
输出结果:
Key = 1 Value = aKey = 2 Value = bKey = 3 Value = cKey = 4 Value = d
二:通过forEach迭代键值对
如果你只想使用键或者值,推荐使用此方式
@Test
public void test2() throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "a");
map.put(3, "c");
map.put(4, "d");
map.put(2, "b");
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}
for (String value : map.values()) {
System.out.println("Value = " + value);
}
}
输出结果:
Key = 1Key = 2 Key = 3 Key = 4Value = aValue = bValue = cValue = d
三:使用迭代器进行遍历
@Test
public void test3() throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "a");
map.put(3, "c");
map.put(4, "d");
map.put(2, "b");
Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>)iterator.next();
Integer key = entry.getKey();
String value = entry.getValue();
System.out.println("Key = " + key + " Value = "+ value);
}
}
输出结果:
Key = 1 Value = aKey = 2 Value = bKey = 3 Value = cKey = 4 Value = d
四:强烈推荐通过Java8 Lambda表达式遍历
@Test
public void test4() throws Exception {
Map<Integer, String> map = new HashMap<>();
map.put(1, "a");
map.put(3, "c");
map.put(4, "d");
map.put(2, "b");
map.forEach((key, value) -> {
System.out.println("Key = " + key + " " + " Value = " + value);
});
}
输出结果:
Key = 1 Value = aKey = 2 Value = bKey = 3 Value = cKey = 4 Value = d