Tuesday, April 11, 2017

Checking that 2 Lists have elements in common

How many times have we created loops to check if any of the elements of one list are contained among any of the elements of other list?

Lists have a contains() and also a containsAll() methods but they doesn't seem to do what we want and we end up writing spaghetti that looks like this often:

1:  boolean isSafeToEat(List<String> allergicFoods) {  
2:    for (String ingredient : getIngredients()) {  
3:      if (allergicFoods.contains(ingredient)) {  
4:        return false;  
5:      }  
6:    }  
7:    return true;  
8:  }  


Sometimes we forget that the Java API has so many useful things. Like this disjoint() method, from Collections.

1:    boolean isSafeToEat(List<String> allergicFoods) {  
2:      return Collections.disjoint(ingredients, allergicFoods);  
3:    }  

Its not Java 8 ;) its being there for a bit already, have a look at this docs:
https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#disjoint(java.util.Collection,%20java.util.Collection)

No comments:

Post a Comment

Share with your friends