1. 让手撕代码的时候,突然忘记了遍历方式,特此进行整理
2. 新建一个map
Map<String, Integer> map = new HashMap<>();
map.put("1", 1);
map.put("2", 2);
2.1 使用map.keySet()进行遍历
for (String key : map.keySet()) {
System.out.println("key:" + key + " --- " + "value:" + map.get(key));
}
2.2 使用entrySet()进行遍历
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("key:" + entry.getKey() + " --- " + "value:" + entry.getValue());
}
2.3 使用iterator进行遍历
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry= iterator.next();
System.out.println("key:" + entry.getKey() + " --- " + "value:" + entry.getValue());
}
2.4 使用forEach进行遍历
map.forEach(new BiConsumer<String, Integer>() {
@Override
public void accept(String s, Integer integer) {
System.out.println(s + " " + integer);
}
});
map.forEach((key, value) -> {
System.out.println("key:" + key + " --- " + "value:" + value);
});
3. 完工,记忆