nested loops involving conditions in java 8 -


i have piece of code

list<obj1> result = new arraylist<obj1>(); (obj1 1 : list1) {             (obj2 2 : list2) {                 if (one.getstatus() == two) {                     result.add(one);                 }             }         } 

in java 8 using streams write this

 list1.stream().foreach(one -> {         if (list2.stream().anymatch(two -> one.getstatus() == two)) {             result.add(one);         }                 }); 

can simplified.

assuming list2 contains unique values , can use equals instead of == obj2, can write this:

list<obj1> result = list1.stream()                          .filter(one -> list2.contains(one.getstatus()))                          .collect(collectors.tolist()); 

though more performant put list2 elements set.


Comments