如何在已经使用lambda遍历另一个列表的同时遍历一个列表?我有1个汽车对象,是我正在遍历的Something对象的列表,在执行此操作时,我需要遍历每个Wheel对象。输出是不同对象Clean的列表。
Car car = new Car();
List<Something> somethings = new ArrayList<Something>();
//say we have multiple items in this List
List<Clean> cleanList =
somethings.stream()
.map(something -> {
return car.wheels.stream().map(wheel -> something.clean(car, wheel)); })
.collect(Collectors.toList());
对于以下对象,
class Car {
String carId;
String carName;
List<Wheel> wheels;
}
class Wheel {
String wheelId;
String wheelType;
}
class Something {
String somethingId;
String somethingType;
public Clean clean(Car car, Wheel wheel) {
return new Clean();
}
}
class Clean {
String cleanId;
String cleanType;
}
我想遍历汽车所有车轮的所有物件。我尝试过这样做,但是没有用。
您需要将其展平,所以flatMap
可以做到
List<Clean> cleanList =
somethings.stream()
.flatMap(something -> car.wheels.stream().map(wheel -> something.clean(car, wheel)))
.collect(Collectors.toList());