简体   繁体   English

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

[英]Java 8 Stream: Populating a list of objects instantiated using values in a HashMap

So I have a HashMap of key-value pairs and would like to create a list of new objects instantiated using each key-value pair. 所以我有一个键值对的HashMap,并希望创建一个使用每个键值对实例化的新对象列表。 For example: 例如:

//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)));
}

How could I go about doing this same thing using Java 8 streams. 我怎样才能使用Java 8流做同样的事情。

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

Note: I have not used forEach(points::add) , because it could result in concurrency issues. 注意:我没有使用forEach(points::add) ,因为它可能导致并发问题。 In general you should be wary of streams with side-effects. 一般来说,你应该警惕带有副作用的溪流。

List<Point> points = new ArrayList<Point>();
coordinates.forEach((i, j) -> points.add(new Point(i, j)));

Here is the possible solution: 这是可能的解决方案:

Map<Integer, Integer> coordinates = new HashMap<Integer, Integer>();
coordinates.put(1,2);
coordinates.put(3,4);

List<Integer> list = coordinates.entrySet().stream()
        .map(entry -> entry.getValue())
        .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM