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

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

Susan Sarandon
Release: 2024-12-03 00:16:11
Original
516 people have browsed it

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

Finding Common Elements in Two Lists

Identifying common elements between two lists is a common requirement in programming. Here's a guide on how you can achieve this using Java's Collection API.

Approach 1: Using Collection#retainAll()

The Collection#retainAll() method can be used to modify an existing list to contain only elements that are also present in another list. This approach is efficient and concise.

List<Integer> listA = new ArrayList<>(Arrays.asList(1, 2, 3));
List<Integer> listB = new ArrayList<>(Arrays.asList(2, 4, 6));

listA.retainAll(listB);
// The resulting listA will now contain only common elements: [2]
Copy after login

Approach 2: Creating a New List with Common Elements

To avoid modifying the original lists, you can create a new one that contains only the common elements. This method is slightly less efficient but preserves the integrity of the original lists.

List<Integer> listA = new ArrayList<>(Arrays.asList(1, 2, 3));
List<Integer> listB = new ArrayList<>(Arrays.asList(2, 4, 6));

List<Integer> common = new ArrayList<>(listA);
common.retainAll(listB);
// The resulting common list will contain only common elements: [2]
Copy after login

Approach 3: Using Java Streams

Java Streams offer a more functional approach to finding common elements. By utilizing the Collection#contains() method, you can filter out non-common elements using Stream#filter().

List<Integer> listA = new ArrayList<>(Arrays.asList(1, 2, 3));
List<Integer> listB = new ArrayList<>(Arrays.asList(2, 4, 6));

List<Integer> common = listA.stream().filter(listB::contains).toList();
// The resulting common list will contain only common elements: [2]
Copy after login

Conclusion

These approaches provide different ways to find common elements in two lists. The choice of method depends on specific requirements, such as performance considerations or the need to modify the original lists.

The above is the detailed content of How Can I Efficiently Find Common Elements in Two Java Lists?. 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