-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?

CurvedHalo
  • 23
  • 7
  • https://stackoverflow.com/questions/57252497/java-8-streams-compare-two-lists-object-values-and-add-value-to-new-list – OldProgrammer Feb 24 '22 at 02:22
  • 1
    The question is, why would you need streams for this in the first place ? – Yassin Hajaj Feb 24 '22 at 07: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.. – CurvedHalo Feb 26 '22 at 17:44

1 Answers1

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]
chasing fish
  • 114
  • 3