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));
}
- easy handling empty conditional collection
- creating stream and another collection
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));
}
- no redundant object
- clearing original collection instead of just return new