Home >Java >javaTutorial >How Can I Efficiently Compare Two Lists in Java to Find Shared and Unique Elements?

How Can I Efficiently Compare Two Lists in Java to Find Shared and Unique Elements?

Linda Hamilton
Linda HamiltonOriginal
2024-12-03 01:05:13595browse

How Can I Efficiently Compare Two Lists in Java to Find Shared and Unique Elements?

Java Compare Two Lists

Comparing two lists to determine the number of shared elements and identify both the similar and different items can be achieved using Java Collections.

To determine the shared elements efficiently, consider using the retainAll method, which modifies the first list to contain only the elements present in both lists. For example, given two lists "milan" and "hafil", the retainAll operation would modify one list to contain only "milan".

To obtain both the similar and different elements, you can utilize a Set. The removeAll method can be employed to exclude any elements from the Set that are not shared between the lists. The resulting Set will contain the similar elements, while the different elements can be obtained by calculating the union of both lists and subsequently excluding the similar elements.

Here is a sample code snippet using a Set for comparison:

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

class Repeated {
    public static void main(String[] args) {
        Collection<String> listOne = Arrays.asList("milan", "iga", "dingo", "elpha", "hafil", "meat", "neeta.peeta");
        Collection<String> listTwo = Arrays.asList("hafil", "iga", "binga", "mike", "dingo");

        Collection<String> similar = new HashSet<>(listOne);
        Collection<String> different = new HashSet<>();
        different.addAll(listOne);
        different.addAll(listTwo);

        similar.retainAll(listTwo);
        different.removeAll(similar);

        System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", listOne, listTwo, similar, different);
    }
}

Output:

One:[milan, iga, dingo, elpha, hafil, meat, neeta.peeta]
Two:[hafil, iga, binga, mike, dingo]
Similar:[dingo, iga, hafil]
Different:[mike, binga, milan, meat, elpha, neeta.peeta]

The above is the detailed content of How Can I Efficiently Compare Two Lists in Java to Find Shared and Unique Elements?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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