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); } }
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); } }
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!