First of all, the existing solution with a loop is just fine. Simply translating it to a solution that uses streams is not an improvement.
Here’s how I would do it. NB: this is not tested.
// Naive version List<String> nameList1 = Arrays.asList("Bill", "Steve", "Mark"); List<String> nameList2 = Arrays.asList("Steve Jobs", "Mark", "Bill"); List<String> matchList = nameList1.stream() .filter(nameList2::contains) .limit(1) .collect(Collectors.toList()); count = matchList.size();
Note that there is no need to both append to a list and increment a count.
If you were going to try to parallelize this, then streams could help, but you would need to do it differently.
Finally, if you are really concerned about performance, and
nameList2.size() == N is large enough, it will be faster to convert
nameList2 to a
HashSet. This turns this from an
O(MN) algorithm to an
(By contrast, parallelizing the naive version only gives you
O(MN/P) complexity at best where P is the number of processes. And that is making some assumptions, and ignoring potential memory contention effects.)