Home >Java >javaTutorial >How to Efficiently Find Common and Unique Elements in Two String Lists Using Java?
Given two lists of strings, the objective is to determine the number of common elements and identify both the shared and unique elements. One possible approach is to leverage Java's ArrayList and HashSet classes.
The ArrayList class provides a convenient method called retainAll. When invoked with another collection, it removes the elements from the calling list that are not present in the argument collection. This can be utilized to identify common elements.
import java.util.ArrayList; ArrayList<String> list1 = new ArrayList<>(); list1.add("milan"); list1.add("dingo"); list1.add("elpha"); list1.add("hafil"); list1.add("meat"); list1.add("iga"); list1.add("neeta.peeta"); ArrayList<String> list2 = new ArrayList<>(); list2.add("hafil"); list2.add("iga"); list2.add("binga"); list2.add("mike"); list2.add("dingo"); list1.retainAll(list2); System.out.println("Common elements: " + list1);
Similar to ArrayList, the HashSet class can be used to eliminate duplicates. By utilizing the addAll and removeAll methods, you can compute both common and unique elements.
import java.util.HashSet; HashSet<String> set1 = new HashSet<>(list1); HashSet<String> set2 = new HashSet<>(list2); // Common elements HashSet<String> common = new HashSet<>(set1); common.retainAll(set2); System.out.println("Common elements: " + common); // Unique elements HashSet<String> unique = new HashSet<>(); unique.addAll(set1); unique.addAll(set2); unique.removeAll(common); System.out.println("Unique elements: " + unique);
These approaches offer efficient ways to compare lists and extract the desired information. Feel free to customize the code to meet your specific requirements.
The above is the detailed content of How to Efficiently Find Common and Unique Elements in Two String Lists Using Java?. For more information, please follow other related articles on the PHP Chinese website!