使用流 API 聚合列表

问题描述 投票:0回答:2

如果你有

class C1{
public List<C2> c2list;
}

class C2{
public List<C3> c3list;
}

然后你想编写一个方法,给定一个 C1 列表,它将聚合 C1 列表中的所有 C3。

public List<C3> getThemll(List<C1> list) {
     list.stream.map(a->a.c2list)
                .map(b->b.c3list)
                .collect(Collectors.toList());
}

这不是给我一个

List<C3>
,而是一个
List<List<C3>>
。我也不确定它是否聚合了每个 C2 的所有 C3。

我错过了什么?

java stream java-stream
2个回答
0
投票
public List<C3> getThemll(List<C1> list) {
     list.stream().flatMap(a->a.c2list.stream())
                  .flatMap(b->b.c3list.stream())
                  .collect(Collectors.toList());
}

这个就可以了。


-1
投票

正如评论中所建议的,这里有一个完整的示例,展示了如何将流的流展平为对象的流(称为流串联): 标题应编辑为“合并流”或“连接列表

  public class Community {

    private List<Person> persons;

    // Constructors, getters and setters
}

--

  public class Person {

    private List<Address> addresses;
      
    // Constructors, getters and setters

  }

--

 public class Address {

    private String city;

    // Constructors, getters and setters

    @Override
    public String toString() {
        return "Address{" +
                "city='" + city + '\'' +
                '}';
    }
  }

演示:

public class AggregationDemo {
    public static void main(String[] args) {
        List<Community> communities = List.of(
                new Community(List.of(new Person(List.of(new Address("Paris"))))),
                new Community(List.of(new Person(List.of(new Address("Florence"))))));

        List<Address> addresses = communities.stream()
                .flatMap(community -> community.getPersons().stream())
                .flatMap(person -> person.getAddresses().stream())
                .collect(Collectors.toList());

        List<List<Person>> collectedListOfList = communities.stream()
                .map(community -> community.getPersons())
                .collect(Collectors.toList());

        addresses.forEach(System.out::println);
        collectedListOfList.forEach(System.out::println);

    }    

}

输出:

Person{addresses=[Address{city='Paris'}]}
Person{addresses=[Address{city='Florence'}]}

[Person{addresses=[Address{city='Paris'}]}]
[Person{addresses=[Address{city='Florence'}]}]
© www.soinside.com 2019 - 2024. All rights reserved.