Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 317
Patan Avatar asked Dec 12 '25 23:12

Patan


1 Answers

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.

like image 191
Tagir Valeev Avatar answered Dec 15 '25 12:12

Tagir Valeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!