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!

6
  • 1
    List<List<Car>> cars = manufacturers.stream() .map(man -> man.getCars()) .collect(Collectors.toList()); Commented Mar 30, 2020 at 14:24
  • 1
    Oh yes, I forgot the second "stream" but this returns still the same error. I will edit the question. Commented Mar 30, 2020 at 14:27
  • 1
    List<List<Car>> result = manufacturers.stream() .map(Manufacturer::getCars) .collect(Collectors.toList()); Commented Mar 30, 2020 at 14:34
  • 1
    @RavindraRanwala This was the correct answer. I was one click away from marking it as the approved answer :) Commented Mar 30, 2020 at 14:36
  • 2
    Ohh I deleted since it is a trivial answer. Let me retract it Commented Mar 30, 2020 at 14:37

1 Answer 1

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());
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.