用stream流遍历Map集合
你可以使用Java 8引入的Stream API来遍历Map集合。Map接口提供了entrySet()方法,它返回一个包含Map.Entry对象的Set视图。每个Map.Entry对象表示一个键值对。
下面是使用Stream API遍历Map集合的示例代码:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
// 使用Stream遍历Map集合
map.entrySet().stream()
.forEach(entry -> System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()));
}
}
在上面的示例中,我们首先创建了一个Map对象,并向其中添加了几个键值对。然后,我们使用entrySet()方法获取Map的Set视图,并通过stream()方法将其转换为Stream对象。最后,我们使用forEach()方法遍历Stream中的每个元素,即Map.Entry对象,并打印键和值。
输出结果将是:
Key: A, Value: 1
Key: B, Value: 2
Key: C, Value: 3