Java 8 嵌套循环进行流式处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35843250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8 nested loops to stream
提问by anton4o
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:
试图通过一个简单的示例来了解 Java 8 流语法。查看了有关此主题的其他类似问题,但找不到与我的示例相匹配并且对我有用的任何解决方案。基本上,我试图用两个嵌套循环重构以下代码段以使用新的流 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?
上面的流语法有什么问题,我错过了什么?
采纳答案by Eran
You can't perform two terminal operations - forEach
and collect
on the same Stream
.
您不能执行两个终端操作 -forEach
并且collect
在同一个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());
回答by fabian
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:
问题是,您正在和返回中创建List
(s) 。这将等效于以下 for 循环:forEach
forEach
void
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:
您可以filter
在cars
流上使用并收集collect
对过滤流的使用以达到所需的结果:
Predicate<Car> carCheck = car -> wheels.stream().anyMatch(wheel -> car.getColor() == wheel.getColor() && wheel.isWorking());
List<Car> filteredCars = cars.stream().filter(carCheck).collect(Collectors.toList());