在Java 8中,能够应用Stream来遍历Map。以下是一些示例代码:
1.遍历Map的键:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.keySet().forEach(key -> System.out.println(key));
2.遍历Map的值:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.values().forEach(value -> System.out.println(value));
3.遍历Map的键值对:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.forEach((key, value) -> System.out.println(key + " : " + value));
4.应用Stream的形式遍历Map的键值对:
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
map.entrySet().stream().forEach(entry ->
System.out.println(entry.getKey() + " : " + entry.getValue()));
以上是几种常见的遍历Map的办法,在Java 8中,应用Stream能够更加简洁和不便地遍历Map。
发表回复