使用流api的java聚合列表

91zkwejq  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(335)

如果你有

  1. class C1{
  2. public List<C2> c2list;
  3. }
  4. class C2{
  5. public List<C3> c3list;
  6. }

然后您想编写一个方法,给定一个c1列表,它将聚合c1列表中的所有c3。

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

这不是给我一个机会 List<C3> ,但是 List<List<C3>> . 我也不确定它是否为每个c2聚合了所有的C3。
我错过了什么?

2g32fytz

2g32fytz1#

  1. public List<C3> getThemll(List<C1> list) {
  2. list.stream.flatmap(a->a.c2list.stream())
  3. .flatmap(b->b.c3list..stream())
  4. .collect(Collectors.toList());
  5. }

这很管用,谢谢

8ulbf1ek

8ulbf1ek2#

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

  1. public class Community {
  2. private List<Person> persons;
  3. // Constructors, getters and setters
  4. }

--

  1. public class Person {
  2. private List<Address> addresses;
  3. // Constructors, getters and setters
  4. }

--

  1. public class Address {
  2. private String city;
  3. // Constructors, getters and setters
  4. @Override
  5. public String toString() {
  6. return "Address{" +
  7. "city='" + city + '\'' +
  8. '}';
  9. }
  10. }

演示:

  1. public class AggregationDemo {
  2. public static void main(String[] args) {
  3. List<Community> communities = List.of(
  4. new Community(List.of(new Person(List.of(new Address("Paris"))))),
  5. new Community(List.of(new Person(List.of(new Address("Florence"))))));
  6. List<Address> addresses = communities.stream()
  7. .flatMap(community -> community.getPersons().stream())
  8. .flatMap(person -> person.getAddresses().stream())
  9. .collect(Collectors.toList());
  10. List<List<Person>> collectedListOfList = communities.stream()
  11. .map(community -> community.getPersons())
  12. .collect(Collectors.toList());
  13. addresses.forEach(System.out::println);
  14. collectedListOfList.forEach(System.out::println);
  15. }

}
输出:

  1. Person{addresses=[Address{city='Paris'}]}
  2. Person{addresses=[Address{city='Florence'}]}
  3. [Person{addresses=[Address{city='Paris'}]}]
  4. [Person{addresses=[Address{city='Florence'}]}]
展开查看全部

相关问题