Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 847
TEXHIK Avatar asked Oct 24 '25 12:10

TEXHIK


2 Answers

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());
}
like image 53
Jude Niroshan Avatar answered Oct 26 '25 02:10

Jude Niroshan


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

like image 39
Michał Marcinkowski Avatar answered Oct 26 '25 02:10

Michał Marcinkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!