Explain Codes LogoExplain Codes Logo

Check if one list contains an element from the other

java
collections
best-practices
performance
Alex KataevbyAlex Kataev·Oct 20, 2024
TLDR
boolean found = !Collections.disjoint(list1, list2);

This efficient line checks for an overlap between list1 and list2 using Collections.disjoint(). It returns true if there are no elements in common, thus we negate it to check for any shared elements.

Use Java stream and anyMatch

Dealing with complex shapes or to compare specific properties, Java streams become our powerful tool:

boolean found = list1.stream().anyMatch(element -> list2.contains(element));

The anyMatch() function stops as soon as it finds a match, acting like our very own superhero, Flash, saving processing power.

Optimizing property comparison

When your objects come with complex fields, perhaps you want to compare a specific attribute:

Set<PropertyType> properties = list2.stream() .map(ObjectType::getProperty) .collect(Collectors.toSet()); boolean found = list1.stream() .map(ObjectType::getProperty) .anyMatch(properties::contains);

The speedily swift Set of properties allows for a quick check against elements from the second list.

Beware of retainAll

retainAll() might feel tempting to use, but remember it's a shady character, altering the list it's called upon. Here's an alternative that doesn't change the original list:

List<Type> copy = new ArrayList<>(list1); copy.retainAll(list2); boolean found = copy.size() > 0;

Guard your list against unwanted changes like a Spartan protecting its homeland!

Tap into Apache Commons

The Apache Commons' library is the James Bond of collection operations: stylish, efficient, and loaded with handy tools:

boolean found = CollectionUtils.containsAny(list1, list2);

Wrapped in a single, suave call, it checks for common elements in a collection.

Check Long objects with care

When specifically dealing with Long attributes, correct implementation of your equals() and hashCode() methods works like well-oiled gears in machine:

Set<Long> list2Ids = list2.stream() .map(ObjectType::getId) .collect(Collectors.toSet()); boolean found = list1.stream() .map(ObjectType::getId) .anyMatch(list2Ids::contains);

Mapping objects to their IDs allows race-car speed comparisons with the efficient set.

Custom attribute comparisons

For a unique attribute, don't forget to:

@Override public boolean equals(Object o) { /* custom equality based on an attribute */ } @Override public int hashCode() { /* hash code based on the same attribute */ }

This empowers collections like Sets and Maps to determine uniqueness and presence. Like finding Waldo in a crowd, it's easier if you know what he looks like!