Reputation: 1361
I have to check whether an arraylist contains any of the value passed through an object.
Consider an arraylist with values "abc", "jkl","def", "ghi".
And String check="abc,ghi"
We have to check whether any of the value in string (abc or ghi) is present in the arraylist and we can stop checking when a match is found.
Traditionally, we can split the String check
with comma and use arraylist.contains()
in iteration for each comma separated values.
But this is time consuming. Is there any better way to do this check.
Upvotes: 1
Views: 6424
Reputation: 25390
This is still O(n), but you could build a set from the search strings and just iterate over the list once:
HashSet<String> checks = new HashSet<String>();
checks.addAll(Arrays.asList(check.split(",")));
for (String item : arraylist) {
if (checks.contains(item)) {
// Found one
}
}
Upvotes: 0
Reputation: 48404
One way would be to use the retainAll
method and Set
s.
Example
// note an additional "ghi" here
List<String> original = new ArrayList<String>(Arrays.asList(new String[]{"abc", "jkl","def", "ghi", "ghi"}));
Set<String> clone = new HashSet<String>(original);
Set<String> control = new HashSet<String>(Arrays.asList(new String[]{"abc","ghi"}));
clone.retainAll(control);
System.out.println(clone.equals(control));
Output
true
Upvotes: 2
Reputation: 7376
You could transform check
into a regexp and loop only once through the ArrayList
.
String check = "abc,ghi";
Pattern p = Pattern.compile("(" + check.replace(',', '|') + ")");
List<String> list = Arrays.asList(new String[] { "abc", "jkl", "def", "ghi" });
for (String element : list) {
if (p.matcher(element).matches()) {
System.out.println("match: " + element);
}
}
Upvotes: 0