Eclipse Collections - Is there a containsAny() method for Sets?

159 Views Asked by At

I can't seem to find a containsAny() method for SetIterable types in Eclipse Collections. Is there one?

MutableSet<String> set1 = Sets.mutable.of("a", "b", "c");
ImmutableSet<String> set2 = Sets.immutable.of("c", "d", "e");

set1.containsAny(set2); // I can't find this method.

It's easy enough to write one:

/**
 * True if [set1] contains any element in [set2].
 */
public static <T> boolean intersects(SetIterable<T> set1, SetIterable<? extends T> set2) {
    return set1.intersect(set2).notEmpty();
}

But I just wanted to know if one already existed.

2

There are 2 best solutions below

0
bliss On

I don't see a containsAny method, but you can do this:

set2.anySatisfy(set1::contains);
0
Donald Raab On

The methods containsAny and containsNone were added to the RichIterable interface in the Eclipse Collections 11.1 release. There are also methods named containsAnyIterable and containsNoneIterable which take Iterable as a parameter instead of Collection.

The following now works using your code example.

MutableSet<String> set1 = Sets.mutable.of("a", "b", "c");
ImmutableSet<String> set2 = Sets.immutable.of("c", "d", "e");
MutableSet<String> set3 = Sets.mutable.of("c", "d", "e");
MutableSet<String> set4 = Sets.mutable.of("d", "e", "f");
ImmutableSet<String> set5 = Sets.immutable.of("d", "e", "f");

Assertions.assertTrue(set1.containsAnyIterable(set2));
Assertions.assertTrue(set1.containsAny(set3));

Assertions.assertFalse(set1.containsAny(set4));
Assertions.assertFalse(set1.containsAnyIterable(set5));

Assertions.assertTrue(set1.containsNone(set4));
Assertions.assertTrue(set1.containsNoneIterable(set5));

I used containsAnyIterable and containsNoneIterable for the ImmutableSet examples because containsAny and containsNone take java.util.Collection as a parameter type and ImmutableSet does not extend this interface. The containsAnyIterable and containsNoneIteable methods work with ImmutableSet because it does extend java.lang.Iterable.