2017-05-14 30 views
2

使用Stream類時可以使用參數創建對象嗎?我想用Java 8 Stream重現以下內容。使用Java 8中的參數創建對象流

for(Integer id:someCollectionContainingTheIntegers){ 
    someClass.getList().add(new Whatever(param1, id)); 
} 

回答

4

當然。但是,如果你有一個集合,你可以使用forEach和拉姆達:

someCollectionContainingTheIntegers.forEach(id -> someClass.getList().add(new Whatever(param1, id)); 

另一個可能的變化是收集到的目的地列表:

someCollectionContainingTheIntegers.stream() 
    .map(id -> new Whatever(param1, id)) 
    .collect(Collectors.toCollection(() -> someClass.getList())); 
+0

非常感謝,Janos :) –

1

做一個foreach列表中的

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

還有一種解決方案...

List<Whatever> collect = someCollectionContainingTheIntegers.stream() 
      .map(id -> new Whatever(param1, id)) 
      .collect(toList()); 
    someClass.getList().addAll(collect);