Reputation: 563
How to traverse through a list while already traversing through another list using lambdas? I have 1 car Object, a list of Something objects which I am traversing and while doing that I need to traverse through every Wheel object. The output is a list of a different object 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());
For the following Objects,
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;
}
I want to traverse through every Something for all Wheels of the Car. I tried doing this but it doesn't work.
Upvotes: 2
Views: 380
Reputation: 23339
You would need to flatten it, so a flatMap
will do
List<Clean> cleanList =
somethings.stream()
.flatMap(something -> car.wheels.stream().map(wheel -> something.clean(car, wheel)))
.collect(Collectors.toList());
Upvotes: 3