Explain Codes LogoExplain Codes Logo

Something like 'contains any' for Java set?

java
stream-api
collections
performance
Alex KataevbyAlex Kataev·Jan 13, 2025
TLDR

In Java, you can quickly examine if a Set overlapped with another collection by employing Collections.disjoint(). This method will return false if there are any common elements:

Set<String> setA = new HashSet<>(Arrays.asList("a", "b")); List<String> listB = Arrays.asList("b", "c"); // Hope you're ready, setA, because 'overlapping' is the new 'sharing'. boolean hasCommon = !Collections.disjoint(setA, listB);

Thorough examination with Stream API, Apache Commons

Fancy footwork with Java 8 Stream API

Java 8 brought along the Stream::anyMatch. Here's how it works:

// Streams are the cool kids on the block. And 'anyMatch' is the coolest of them all. boolean hasCommon = setA.stream().anyMatch(listB::contains);

This quickly gets translated to: "If any element in Set A matches any element in List B, they have common elements."

The Apache commons touch

Got Apache Commons Collections at your rescue? Employ CollectionUtils.containsAny for simplicity:

// Some say Apache does the common uncommonly well boolean hasCommon = CollectionUtils.containsAny(setA, listB);

Just make sure your Set and the other collection are compatible in terms of type (otherwise, expect a ClassCastException party)!

Stream API backflips and Guava techniques

Flexibility delight with Stream API

Combine Stream API with methods like filter or map and tap into the power of complex checks:

// Stream API, take the wheel! boolean hasCommon = setA.stream() .map(/* complex mapping */) .anyMatch(listB::contains);

Guava’s twilight zone

With Google's Guava library, Sets.intersection could be your go-to method:

// Guava to the intersection rescue! boolean hasCommon = !Sets.intersection(setA, Set.copyOf(listB)).isEmpty();

Just remember: Including a new library for this little feature may not be the best idea!

Think performance, think clever

Stream::anyMatch values your time, stopping instantly on finding a match. However, Sets.intersection (Guava) or CollectionUtils.containsAny (Apache Commons) are not so generous, and may affect performance.

Refer-to-the book time

  1. The Collections Framework - turbo charge your mastery over Java Collections API.
  2. Collections – Home - Apache Commons Collections, there to lift your Java Collections Framework game.
  3. GitHub - google/guava: Google core libraries for Java - Guava: the core libraries for the java enthusiasts.
  4. java - Replace "'" with any other character with String's replace() - Stack Overflow - Set intersection or contains_any questions? This might just be the answer.
  5. java.util.stream (Java Platform SE 8 ) - Enriching journey through Java Stream API.
  6. Trail: Collections (The Java™ Tutorials) - Your bookmarked Java guide on collections, lavished with useful examples and clarifications.