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