Finding Common Elements in Lists
To identify the shared elements between two lists, you can employ Collection#retainAll(). By utilizing this method, you can conveniently retain only the elements present in both lists, effectively eliminating any unique elements from either list.
listA.retainAll(listB); // listA now contains only the elements also contained in listB.
Alternatively, if you wish to preserve the original listA, you can create a new list to hold the common elements:
List<Integer> common = new ArrayList<>(listA); common.retainAll(listB); // common now contains only the elements contained in both listA and listB.
For enthusiasts of streams, a clever approach involves filtering based on containment using Stream#filter() and Collection#contains():
List<Integer> common = listA.stream().filter(listB::contains).toList(); // common now contains only the elements contained in both listA and listB.
While this may appear more concise, it is also at least twice slower in execution.
The above is the detailed content of How Can I Find Common Elements Between Two Lists in Java?. For more information, please follow other related articles on the PHP Chinese website!