0

I can't get my head around this problem.

Problem

I want to writhe this with Java streams:

List<Manufacturer> manufacturers = ... // List of Manufacturer-Objects

List<List<Car>> cars = new ArrayList<>();
for (Manufacturer man : manufacturers) {
   cars.add(man.getCars()); // Let's just say getCars() returns a List of cars.
}

I think with Java Streams it should look like the following:

List<List<Car>> cars = manufacturers.stream().
   .flatMap(man -> man.getCars().stream())
   .collect(Collectors.toList());

Errors

But my IDE says the following no instance(s) of type variable(s) R exist so that List<Event> conforms to Stream<? extends R>

And the java compiler:

java: incompatible types: cannot infer type-variable(s) R
    (argument mismatch; bad return type in lambda expression
      java.util.List<elements.Car> cannot be converted to java.util.stream.Stream<? extends R>)

Any solutions for this? Thanks!

Philipp
  • 335
  • 1
  • 6
  • 17

1 Answers1

4

The issue here is that you are using the flatMap operator which takes all the lists and gives you a List<Car>. Instead you have to use the map operator to get the desired result. Here's how it looks.

List<List<Car>> result = manufacturers.stream()
    .map(Manufacturer::getCars)
    .collect(Collectors.toList());
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63