【问题标题】:Java 8 Stream: Populating a list of objects instantiated using values in a HashMapJava 8 Stream:填充使用 HashMap 中的值实例化的对象列表
【发布时间】:2017-02-15 19:03:41
【问题描述】:

所以我有一个键值对的 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)));
}

我如何使用 Java 8 流来做同样的事情。

【问题讨论】:

    标签: java java-8 java-stream


    【解决方案1】:
        List<Point> points = coordinates.entrySet().stream()
                .map(e -> new Point(e.getKey(), e.getValue()))
                .collect(Collectors.toList());
    

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

    【讨论】:

    • 感谢您的回答!简洁明了。
    【解决方案2】:
    List<Point> points = new ArrayList<Point>();
    coordinates.forEach((i, j) -> points.add(new Point(i, j)));
    

    【讨论】:

      【解决方案3】:

      这是可能的解决方案:

      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());
      

      【讨论】:

      • 结果应该是一个点列表。
      猜你喜欢
      • 2021-01-08
      • 2019-06-26
      • 2020-06-10
      • 1970-01-01
      • 2017-03-08
      • 2017-09-26
      • 2015-10-24
      相关资源
      最近更新 更多