Java 8 Stream:使用HashMap中的值填充实例化的对象列表

iSe*_*Jay 2 java java-8 java-stream

所以我有一个键值对的HashMap,并希望创建一个使用每个键值对实例化的新对象列表.例如:

//HashMap of coordinates with the key being x and value being y
Map<Integer, Integer> coordinates = new HashMap<Integer, Integer>();
coordinates.put(1,2);
coordinates.put(3,4);

List<Point> points = new ArrayList<Point>();

//Add points to the list of points instantiated using key-value pairs in HashMap
for(Integer i : coordinates.keySet()){
     points.add(new Point(i , coordinates.get(i)));
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能使用Java 8流做同样的事情.

Pat*_*ker 8

    List<Point> points = coordinates.entrySet().stream()
            .map(e -> new Point(e.getKey(), e.getValue()))
            .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

注意:我没有使用过forEach(points::add),因为它可能导致并发问题.一般来说,你应该警惕带有副作用的溪流.