-2

If you have

class C1{
public List<C2> c2list;
}

class C2{
public List<C3> c3list;
}

then you want to write a method, that given a list of C1, it will aggregate all the C3s that are in the list of C1s.

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

This is not giving me a List<C3>, but a List<List<C3>>. I'm also not sure if its aggregating all the C3s for every C2.

What am I missing?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Facundo Laxalde
  • 305
  • 5
  • 18

2 Answers2

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

this does the trick, thanks

Facundo Laxalde
  • 305
  • 5
  • 18
-1

As suggested in the comments, here a full example showing how to flatten out a stream of streams to a stream of an object (known as Stream concatenation): The title should be edited to "Merge Streams" or "Concatenate lists"

  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 + '\'' +
                '}';
    }
  }

Demo:

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

    }    

}

Output:

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

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