-1

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.

    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?

3
  • stackoverflow.com/questions/57252497/… Commented Feb 24, 2022 at 2:22
  • 1
    The question is, why would you need streams for this in the first place ? Commented Feb 24, 2022 at 7:31
  • I was under the impression Streams were an optimized way of doing list comprehensions, rather than enhanced for loops? Essentially I wanted to stream over the lists do two filters, each one giving a separate outcome.. Commented Feb 26, 2022 at 17:44

1 Answer 1

1

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]
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.