Question:
There are 2 string sheets: List<String> fileList
and List<String> arr
. It is required to display how many words in fileList are contained in arr, I did this:
fileList
.stream()
.filter(s -> arr
.stream()
.anyMatch(s::equals)
)
.count();
Is this approach correct? Or is there some better way?
Answer:
It will be faster and easier to use the intersection of sets:
Set<String> set = new HashSet<>(fileList);
set.retainAll(new HashSet<String>(arr));
int count = set.size();
And if you already use streams, then do not produce them for each element. It will be more efficient like this:
long count = fileList.stream()
.filter(arr::contains)
.count();