2

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.

0

1 Answer 1

3

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.