nested loops involving conditions in java 8

I have a piece of code

List<Obj1> result = new ArrayList<Obj1>();
for (Obj1 one : list1) {
            for (Obj2 two : list2) {
                if (one.getStatus() == two) {
                    result.add(one);
                }
            }
        }

In Java 8 Using streams I could write like this

 list1.stream().forEach(one -> {
        if (list2.stream().anyMatch(two -> one.getStatus() == two)) {
            result.add(one);
        }            
    });

can this be much simplified.

Answer

Assuming that list2 contains unique values and you can use equals instead of == for Obj2, you can write it like this:

List<Obj1> result = list1.stream()
                         .filter(one -> list2.contains(one.getStatus()))
                         .collect(Collectors.toList());

Though it would be more performant to put the list2 elements to the Set.

Leave a Reply

Your email address will not be published. Required fields are marked *