[英]Java Streams instead of nested for loops
Lets say I have two lists of cars, and I want to stream through them, firstly checking they are the same type, and then and compare them based on some features, and depending on the outcomes I will perform some logic.假设我有两个汽车列表,我想 stream 通过它们,首先检查它们是同一类型,然后根据某些特征比较它们,并根据结果执行一些逻辑。
for(Car newCar : newCarLot) {
for(Car oldCar : oldCarLot) {
if(oldCar.getType() == newCar.getType()) {
if(oldCar.getTransmission() == newCar.getTransmission()) {
// do something, for example println
}
if(oldCar.getColour() == newCar.getColour()) {
// do something else
}
}
}
}
How would I perform this in streams?我将如何在流中执行此操作?
Something like this one?像这样的东西?
public class Main {
public static void main(String[] args) {
List<Integer> numbers1 = Arrays.asList(1, 2, 3);
List<Integer> numbers2 = Arrays.asList(3, 4);
numbers1.stream().flatMap(
a -> numbers2.stream().map(b -> new int[]{a, b})
).collect(Collectors.toList()).forEach(c -> System.out.println(Arrays.toString(c)));
}
}
Result:结果:
[1, 3]
[1, 4]
[2, 3]
[2, 4]
[3, 3]
[3, 4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.