Nested lists with streams in Java8

前端 未结 4 1260
感动是毒
感动是毒 2020-12-05 23:42

I have a list of objects A. Each object A in this list contains list of object B and the object B contains list of Object C. The object C contains an attribute name that i w

4条回答
  •  -上瘾入骨i
    2020-12-06 00:43

    You can do it with flatMap.

    I made an example with Company which contains a list of Person :

    public static void main(String[] args) {
        List companies = Arrays.asList(
                new Company(Arrays.asList(new Person("Jon Skeet"), new Person("Linus Torvalds"))),
                new Company(Arrays.asList(new Person("Dennis Ritchie"), new Person("Bjarne Stroustrup"))),
                new Company(Arrays.asList(new Person("James Gosling"), new Person("Patrick Naughton")))
        );
    
        List persons = companies.stream()
                .flatMap(company -> company.getPersons().stream())
                .map(Person::getName)
                .collect(Collectors.toList());
    
        System.out.println(persons);
    }
    

    Output :

    [Jon Skeet, Linus Torvalds, Dennis Ritchie, Bjarne Stroustrup, James Gosling, Patrick Naughton]

提交回复
热议问题