[英]How to build a new list containing all entries from existing list AND a copy of each entry with one field modified?
我有一個名為列表的 Object 列表。 使用 list.stream(),我需要創建一個相同 Object 的新列表,其中新列表包含所有原始條目,並且新列表包含每個條目的副本,其中一個字段已修改。 我知道如何使用 list.stream() 兩次,但我想在 1 stream 下進行。
這就是我使用 list.stream() 兩次完成任務的方式
newList = list.stream().collect(Collectors.toList());
newList.addAll(list.stream().map(l -> {SomeObject a = new SomeObject(l);
a.setField1("New Value");
return a;
}).collect(Collectors.toList())
);
使用flatMap
(假設您不介意交錯的原始值和派生值):
newList = list.stream()
.flatMap(l -> {
SomeObject a = new SomeObject(l);
a.setField1("New Value");
return Stream.of(l, a);
})
.collect(toList());
如果只是不想使用stream()
兩次,則可以避免使用第一個addAll
; 以及第二個不必要的collect
:
newList = new ArrayList<>(list.size() * 2);
newList.addAll(list);
list.stream()
.map(l -> {
SomeObject a = new SomeObject(l);
a.setField1("New Value");
return a;
})
.forEach(newList::add);
如果你想要 objct 然后處理 object 等等,那么在你的新列表中,你可以嘗試這樣的事情:
List<String> list = List.of("a", "b", "c" );
List<String> answer = list.stream()
.map(s -> List.of(s,s+"1"))
.flatMap(List::stream).collect(Collectors.toList());
System.out.println(answer);
Output:
[a, a1, b, b1, c, c1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.