I need a method, which filter out a collection by checking if the element's field is contained in another collection's element's field. Which way is better:
A method, returning filtered collection:
List method1(List foo, List bar){
if(bar.isEmpty())
return Collections.emptyList();
Set<Integer> ids = bar.stream().map(elem->elem.getId).collect(Collectors.toSet());
return foo.stream().filter(elem->ids.contains(elem.barId));
}
Or a method, modifying the original collection:
void method2(List foo, List bar){
if(bar.isEmpty()){
foo.clear();
return;
}
Set<Integer> ids = bar.stream().map(elem->elem.getId).collect(Collectors.toSet());
foo.removeIf(elem->ids.contains(elem.barId));
}
Your method1 & method2 will not work as you expected as it does not have a terminal operation in your last stream on foo. It is recommended to use immutable approach whenever possible as it leads to less error-prone code and easy to understand the code behaviour. You should read about this
List method1(List foo, List bar){
if (bar.isEmpty())
return Collections.emptyList();
final Set<Integer> barIds = getIds(bar);
return foo.stream()
.filter(elem->barIds.contains(elem.barId))
.collect(Collectors.toList());
}
private Set<Integer> getIds(final List bar) {
return bar.stream()
.map(elem->elem.getId)
.collect(Collectors.toSet());
}
First approach is imho better. Out parameter concept in real life is hard to maintain.
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