By TEXHIK


2019-09-11 09:14:21 8 Comments

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

3 comments

@Jude Niroshan 2019-09-12 13:19:03

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();

    Set<Integer> ids = getIds(bar);
    return foo.stream()
              .filter(elem->ids.contains(elem.barId))
              .collect(Collectors.toList());
}

private Set<Integer> getIds(List bar) {

  return bar.stream()
            .map(elem->elem.getId)
            .collect(Collectors.toSet());
}

@MichaƂ Marcinkowski 2019-09-12 13:00:01

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

@Sterconium 2019-09-11 10:05:23

A method that returns a different version of the input, instead of modifying it, is a method which input is passed by value, a strategy compliant to how Java was designed. The other way around is a method which input is passed by reference, the way C works. As you just proved it is possible to do this in Java too, but it is more a "workaround" than a feature. (More info on this)

Not saying you which version is better, but I would use the first one if in doubt.

Hope I helped.

Related Questions

Sponsored Content

23 Answered Questions

2 Answered Questions

[SOLVED] Java Optional orElseThrow with empty collection

6 Answered Questions

[SOLVED] In Java streams is peek really only for debugging?

27 Answered Questions

[SOLVED] What is the best way to filter a Java Collection?

11 Answered Questions

[SOLVED] Ways to iterate over a list in Java

2 Answered Questions

[SOLVED] Mapping objects using java8

1 Answered Questions

3 Answered Questions

[SOLVED] Java 8 Filter and Collect of List<Map<String, Object>>

Sponsored Content