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

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

Mary-Kate Olsen
Release: 2024-12-08 10:57:16
Original
246 people have browsed it

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

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

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

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

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!

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