I have a list testEle
which contains 100 elements. I am iterating over it an need to filter only the values which contains anyone of elements in second list finalList
{a1,a2,a3...so on}
testEle.stream().filter( x -> x.matches(// any one of finalList element here))
I am not sure what should be inside the .matches()
or if I should be using something else ?
CodePudding user response:
matches is a String function to test a regular expression on it. Just check with List::contains.
testEle.stream().filter( x -> finalList.contains(x))
CodePudding user response:
I have a list
testEle
which contains 100 elements. I am iterating over it an need to filter only the values which contains anyone of elements in second listfinalList
.
Since contain()
check has a cost O(n) depending on the size of the finalList
it might make sense to store its values into a HashSet
and perform checks against the set.
Set<Foo> set = new HashSet<>(finalList);
testEle.stream().filter(set::contains)...
From the OP's comment:
I need case insensitive comparison. So how to do that ?
finalList.contains.equalsIgnoreCase
type something
Then you can create a stream over the finalList
inside the filter and apply Stream.anyMacth()
as a terminal operation of the nested stream.
List<Foo> finalList = // initializing the list
testEle.stream().filter(x ->
finalList.stream().anyMatch(y -> y.equalsIgnoreCase(x))
)...