How to Check if an ArrayList Contain 2 values?

前端 未结 6 1191
忘掉有多难
忘掉有多难 2021-01-19 09:34

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 loo

6条回答
  •  伪装坚强ぢ
    2021-01-19 10:18

    You can also do

    String person1 = "Joe Smith"; // contains "Joe"
    String person2 = "Jasha Thompson"; // contains "Jasha"
    String person3 = "Jasha Joesephson"; // contains "Joe" and "Jasha"
    String person4 = "Steve Smith"; // contains neither
    
    public boolean containsJoeOrJasha(String stringToCheck) {
      return !Collections.disjoint(
        Arrays.asList(stringToCheck.split(" ")),
        Arrays.asList("Joe", "Jasha"));
    }
    

    Collections.disjoint returns true if the two collections are disjoint, meaning that they have no elements in common. So...

    jshell> containsJoeOrJasha(person1)
    $33 ==> true
    
    jshell> containsJoeOrJasha(person2)
    $34 ==> true
    
    jshell> containsJoeOrJasha(person3)
    $35 ==> true
    
    jshell> containsJoeOrJasha(person4)
    $36 ==> false
    

提交回复
热议问题