问题
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");
回答1:
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;
}
}
回答2:
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:
回答3:
Simply use Arrays class
person.containsAll(Arrays.asList("Jasha","Joe"));
回答4:
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.
回答5:
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
回答6:
You have to search each string.
UPDATED
List list=new ArrayList();
list.add("Joe");
list.add("Jasha");
if(person.containsAll(list))
{
//do something
}
来源:https://stackoverflow.com/questions/20755432/how-to-check-if-an-arraylist-contain-2-values