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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With