Home > Java > javaTutorial > How Can I Find Common Elements Between Two Lists in Java?

How Can I Find Common Elements Between Two Lists in Java?

Linda Hamilton
Release: 2024-12-12 15:49:09
Original
162 people have browsed it

How Can I Find Common Elements Between Two Lists in Java?

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.
Copy after login

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.
Copy after login

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.
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template