Search code examples
javacollectionsarraylist

How to Check if an ArrayList Contain 2 values?


is there any way to check if a collection contain a value or more with better performance than looping twice with contains?

in other meaning something that would look like this

person.contains("Joe" || "Jasha");

Solution

  • The implementation of ArrayList.contains() loops through every element and does an equals() test, so calling .contains() twice is inefficient.

    You could write your own loop that check both at once using a compiled regex Pattern that looks for either name at the same time:

    Pattern p = Pattern.compile("Joe|Jasha");
    boolean found = false;
    for (String s : person) {
        if (p.matcher(s).find()) {
            found = true;
            break;
        }
    }