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

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

Linda Hamilton
Release: 2024-12-07 04:06:18
Original
751 people have browsed it

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

Finding Common Elements in Two Lists

In this programming scenario, we aim to determine the number of common elements between two lists, along with identifying both the similar and distinct values.

To achieve this, one can utilize Java's collection framework and specifically the ArrayList or HashSet classes. The retainAll method in ArrayList retains only the items that are shared by both lists, providing a count of the common elements (three in this case).

For example:

import java.util.ArrayList;
import java.util.Arrays;

public class CompareLists {
    public static void main(String[] args) {
        ArrayList<String> list1 = new ArrayList<>(Arrays.asList("milan", "dingo", "iga", "elpha", "hafil", "meat", "iga", "milan", "elpha", "meat", "iga"));
        ArrayList<String> list2 = new ArrayList<>(Arrays.asList("hafil", "iga", "binga", "mike", "dingo", "dingo", "dingo"));

        list1.retainAll(list2);
        System.out.println(list1);
    }
}
Copy after login

Alternatively, using HashSet for the second list allows for more efficient comparison:

import java.util.HashSet;
import java.util.Arrays;

public class CompareLists {
    public static void main(String[] args) {
        ArrayList<String> list1 = new ArrayList<>(Arrays.asList("milan", "dingo", "iga", "elpha", "hafil", "meat", "iga", "milan", "elpha", "meat", "iga"));
        HashSet<String> list2 = new HashSet<>(Arrays.asList("hafil", "iga", "binga", "mike", "dingo", "dingo", "dingo"));

        Set<String> common = new HashSet<>(list1);
        common.retainAll(list2);

        Set<String> unique = new HashSet<>(list1);
        unique.addAll(list2);
        unique.removeAll(common);

        System.out.println("Common: " + common);
        System.out.println("Distinct: " + unique);
    }
}
Copy after login

This version identifies both common and distinct values, handling repeated values effectively.

The above is the detailed content of How Can I Efficiently Find Common and Distinct 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