How to check if any of multiple elements are in a List in a convenient way?

Viewed 2170

I'm trying to write the following condition:

if(javaList.contains("aaa")||javaList.contains("abc")||javaList.contains("abc")) {
    //do something
}

How can I do it in a better way?

3 Answers

It's usually more efficient to run contains on a Set than on a List. Therefore I suggest you create a Set of the elements you want to test, and then stream over the List to see if any of its elements matches:

How about:

if (javaList.stream().anyMatch(e -> Set.of("aaa","abc","def").contains(e)))

If you're on java 8 and higher, you can use the following code :

if (javaList.stream().anyMatch(l -> l.matches("aaa|xyz|abc")))

You can use .matches() and pass in the Strings separated by the OR symbol. The .matches() takes in a String, represented as a regex.

Convert to Set and check the intersection.

Set<String> intersection = new HashSet<String>(listOfThings);
intersection.retainAll(Set.of("aaa","abc","def"));

Check if size > 0 and then you can also see what things it contained, it that is of interest.

Related