.removeIf() vs .filter().collect()

TEXHIK :

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
Michał Marcinkowski :

First approach is imho better. Out parameter concept in real life is hard to maintain.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328251&siteId=1