簡體   English   中英

使用Java 8 Stream中的參數創建對象

[英]Creating objects with parameters in Java 8 Stream

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

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

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

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

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

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

另一個解決方案......

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

在列表中做一個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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM