Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 743
John Humanyun Avatar asked Oct 25 '18 12:10

John Humanyun


1 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)))
like image 52
Eran Avatar answered Oct 03 '22 08:10

Eran