3

I have a list of class R with list of other class P

List<R> rList = getRListFromDb();

I would like to get the all the P objects in another list

List<P> result = new ArrayList<>();

I tried these, but giving me Class cast exception, saying class P cannot be converted to class R. By the way I have seen issue given below, but tried and could not figure it out.

How can I turn a List of Lists into a List in Java 8?

1. rList.stream().map(R::getP).flatMap(List::stream).forEach(result::addAll);
2. rList.forEach(r -> result.addAll(r.getP()));

I would like to what is incorrect here and also would like to know different ways of getting this done in Java 8.

Ganesh Shenoy
  • 619
  • 1
  • 10
  • 28
  • Possible duplicate of [How can I turn a List of Lists into a List in Java 8?](https://stackoverflow.com/questions/25147094/how-can-i-turn-a-list-of-lists-into-a-list-in-java-8) – Robby Cornelissen Oct 02 '18 at 10:14

1 Answers1

5
rList.stream().map(R::getP).flatMap(List::stream).forEach(result::addAll);

would work if you didn't use flatMap (since addAll requires a Collection, but flatMap transforms your Stream<List<P>> to a Stream<P>.

This would work:

rList.stream().map(R::getP).forEach(result::addAll);

With flatMap it should be:

rList.stream().map(R::getP).flatMap(List::stream).forEach(result::add);

That said, the correct way is to use collect:

List<P> result = rList.stream()
                      .map(R::getP)
                      .flatMap(List::stream)
                      .collect(Collectors.toList());

or

List<P> result = rList.stream()
                      .flatMap(r -> r.getP().stream())
                      .collect(Collectors.toList());
Eran
  • 387,369
  • 54
  • 702
  • 768