Retrieving Common Elements from Two Lists
When working with collections in Java, you may encounter situations where you need to find the common elements shared by multiple lists. There are several approaches you can take to accomplish this task.
Using Collection#retainAll()
The Collection#retainAll() method provides a straightforward solution for finding common elements. It updates the calling list (listA) by removing all elements that are not also contained in the specified collection (listB). This effectively retains only the common elements.
listA.retainAll(listB); // listA now contains only common elements
Creating a New List
If you prefer to preserve the original lists, you can create a new list called common. This list is initially populated with the elements from listA, and then the retainAll() method is used to filter out the non-common elements.
List<Integer> common = new ArrayList<>(listA); common.retainAll(listB); // common now contains only common elements
Utilizing Stream#filter()
For those who favor streams, you can leverage the Stream#filter() method. This approach involves checking if each element from listA is present in listB using Collection#contains(). Elements that satisfy this condition are added to the common list.
List<Integer> common = listA.stream().filter(listB::contains).toList(); // common now contains only common elements
Note: While this method provides flexibility, it tends to be slower than the other approaches.
The above is the detailed content of How Can I Efficiently Find Common Elements Between Two Lists in Java?. For more information, please follow other related articles on the PHP Chinese website!