Java 8 nested loop flow
•
Java
Try to understand java 8 stream syntax through a simple example Look at other similar problems on this topic, but I can't find any solutions that match my example and are useful to me Basically, I'm trying to refactor the following code snippet using two nested loops to use the new flow 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;
The management obtains the returned void:
return cars.stream().forEach( car -> wheels.stream() .filter(wheel -> wheel.getColor() == car.getColor() && wheel.isWorking() == true) .collect(Collectors.toList()));
What's wrong with the stream syntax above? What did I miss?
Solution
You cannot perform two terminal operations – foreach and collect data on the same stream
Instead, you need to filter the list of cars by checking whether each car has a matching work wheel:
List<Car> filteredCars = cars.stream() .filter ( car -> wheels.stream() .anyMatch(wheel -> wheel.getColor() == car.getColor() && wheel.isWorking())) .collect(Collectors.toList());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码