Something like 'contains any' for Java set?
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:
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:
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:
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:
Guava’s twilight zone
With Google's Guava library, Sets.intersection
could be your go-to method:
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
- The Collections Framework - turbo charge your mastery over Java Collections API.
- Collections – Home - Apache Commons Collections, there to lift your Java Collections Framework game.
- GitHub - google/guava: Google core libraries for Java - Guava: the core libraries for the java enthusiasts.
- java - Replace "'" with any other character with String's replace() - Stack Overflow - Set intersection or contains_any questions? This might just be the answer.
- java.util.stream (Java Platform SE 8 ) - Enriching journey through Java Stream API.
- Trail: Collections (The Java™ Tutorials) - Your bookmarked Java guide on collections, lavished with useful examples and clarifications.
Was this article helpful?