2

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.

Luke
  • 2,151
  • 3
  • 17
  • 15

2 Answers2

2

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

set2.anySatisfy(set1::contains);
bliss
  • 336
  • 2
  • 8
0

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.

Donald Raab
  • 6,458
  • 2
  • 36
  • 44