2017-02-15 4 views
2

私はキーと値のペアのHashMapを持っており、各キーと値のペアを使ってインスタンス化された新しいオブジェクトのリストを作成したいと思います。例:Java 8ストリーム: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ストリームを使用してこの同じことを行う方法を教えてください。

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

答えて

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

注:ここでは

+0

答えをありがとう!明確かつ簡潔です。 – iSeeJay

0

は可能な解決策である、それは並行性の問題につながる可能性があるため、私は、forEach(points::add)を使用していません。一般的に、副作用のあるストリームを注意する必要があります。

+3

結果は、ポイントのリストであると考えられます。 –

+1

@ greg-449良い点! – ioseb

2
List<Point> points = new ArrayList<Point>(); 
coordinates.forEach((i, j) -> points.add(new Point(i, j))); 
関連する問題