如何构建一个新列表,其中包含现有列表中的所有条目以及修改了一个字段的每个条目的副本?

How to build a new list containing all entries from existing list AND a copy of each entry with one field modified?

我有一个名为列表的对象列表。使用 list.stream(),我需要创建同一对象的新列表,其中新列表包含所有原始条目,新列表包含每个条目的副本,其中一个字段已修改。我知道如何使用 list.stream() 两次执行此操作,但我想在 1 个流下执行此操作。

这就是我使用 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);

如果你想要对象然后处理对象等等,那么在你的新列表中,你可以尝试这样的事情:

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

输出:

[a, a1, b, b1, c, c1]