Streamクラスを使用しているときに、パラメータ付きのオブジェクトを作成することは可能ですか?私はJava 8 Streamで次のように再現したいと思います。Java 8 Streamでパラメータを持つオブジェクトを作成する
for(Integer id:someCollectionContainingTheIntegers){
someClass.getList().add(new Whatever(param1, id));
}
Streamクラスを使用しているときに、パラメータ付きのオブジェクトを作成することは可能ですか?私はJava 8 Streamで次のように再現したいと思います。Java 8 Streamでパラメータを持つオブジェクトを作成する
for(Integer id:someCollectionContainingTheIntegers){
someClass.getList().add(new Whatever(param1, id));
}
です。あなたは、コレクションを持っている場合しかし、あなたはforEach
とラムダを使用することができます。
someCollectionContainingTheIntegers.stream()
.map(id -> new Whatever(param1, id))
.collect(Collectors.toCollection(() -> someClass.getList()));
がリスト
List<Integer> ml = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
List<Integer> ml2 = Arrays.asList(21, 22, 23, 24);
ml2.forEach(x -> ml.add(x));
System.out.println(ml);
でforeachの操作を行います。別の可能な変動は、宛先リストに集めることである
someCollectionContainingTheIntegers.forEach(id -> someClass.getList().add(new Whatever(param1, id));
もう1つの解決策...
List<Whatever> collect = someCollectionContainingTheIntegers.stream()
.map(id -> new Whatever(param1, id))
.collect(toList());
someClass.getList().addAll(collect);
ありがとう、Janos :) –