2017-02-15 52 views
2

因此,我有一個HashMap的鍵 - 值對,並希望創建使用每個鍵 - 值對實例化的新對象的列表。例如:Java 8 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))); 
} 

我該如何去做關於使用Java 8流做同樣的事情。

回答

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

注:我沒有用過forEach(points::add),因爲這可能會導致併發問題。一般來說,你應該警惕具有副作用的流。

+0

感謝您的回答!清晰簡潔。 – iSeeJay

0

以下是可能的解決方案:

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

結果應該是點的列表。 –

+1

@ greg-449好點! – ioseb

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