Java 8 nested loops to stream

Viewed 45783

Trying to get my head round the Java 8 streams syntax with a simple example. Had a look at the other similar questions on this topic, but could not find any solutions that would match my example and would work for me. Basically I am trying to refactor the following snippet with two nested loops to use the new stream API:

List<Car> filteredCars = new ArrayList<>();

for (Car car : cars) {
    for (Wheel wheel : wheels) {
        if (car.getColor() == wheel.getColor() &&
                wheel.isWorking() == true ) {
            filteredCars.add(car);
            break;
        }
    }
}

return filteredCars;

Managed to come up with this which returns void:

return cars.stream().forEach(
    car -> wheels.stream()
        .filter(wheel -> wheel.getColor() == car.getColor() &&
                    wheel.isWorking() == true)
        .collect(Collectors.toList()));

What is wrong with the stream syntax above and what am I missing?

2 Answers
Related