Java 8 nested loops to stream
You can't perform two terminal operations - forEach
and collect
on the same Stream
.
instead, you need to filter the cars list by checking for each car if it has a matching working wheel :
List<Car> filteredCars =
cars.stream()
.filter (
car -> wheels.stream()
.anyMatch(wheel -> wheel.getColor() == car.getColor() &&
wheel.isWorking()))
.collect(Collectors.toList());
The problem is, you're creating the List
(s) inside the forEach
and forEach
returns void
. This would be the equivalent of the following for loop:
for (Car car : cars) {
List<Car> filteredCars = new ArrayList<>();
for (Wheel wheel : wheels) {
if (car.getColor() == wheel.getColor() &&
wheel.isWorking() == true ) {
filteredCars.add(car);
break;
}
}
}
return filteredCars; // whoops cannot be accessed (scope) !!!
You could use filter
on the cars
stream and collect the use collect
on the filtered stream to achieve the desired results:
Predicate<Car> carCheck = car -> wheels.stream().anyMatch(wheel -> car.getColor() == wheel.getColor() && wheel.isWorking());
List<Car> filteredCars = cars.stream().filter(carCheck).collect(Collectors.toList());