使用流api的java聚合列表

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

如果你有

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。
我错过了什么?

2g32fytz

2g32fytz1#

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

这很管用,谢谢

8ulbf1ek

8ulbf1ek2#

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

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'}]}]

相关问题