How to Check if an ArrayList Contain 2 values?

前端 未结 6 1188
忘掉有多难
忘掉有多难 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:07

    You have to search each string.

    UPDATED

    List list=new ArrayList();
    list.add("Joe");
    list.add("Jasha");
    if(person.containsAll(list))
    {
       //do something
    }
    
    0 讨论(0)
  • 2021-01-19 10:09

    contains takes only one param

    if(person.contains("Joe") || person.contains("Jasha")){
      // do something
      }
    

    If you are worrying about N number of elements

    String[] items ={"Joe","jon","And So On".....};
    for (String item : items ) {
        if (person.contains(item)) {
           //found
            break; 
        } 
    }
    

    Edit:

    That || is most helpful in your case, since you have the benefit of Short-circuit_evaluation

    The second argument is only executed or evaluated if the first argument does not suffice to determine the value of the expression:

    0 讨论(0)
  • 2021-01-19 10:09

    Simply use Arrays class

    person.containsAll(Arrays.asList("Jasha","Joe"));
    
    0 讨论(0)
  • 2021-01-19 10:14

    You can also use regex as follows:

    person.toString().matches(".*\\b(Joe|Jasha)\\b.*");
    

    You will get a boolean value indicating whether it is present or not.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-19 10:25

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题