If you’re preparing for upcoming interviews or simply looking to boost your ArrayList mastery, join us as we demystify this key skill for Java developers or Automation engineers. Whether you’re new to Java or an experienced developer, this tutorial takes a practical approach so you can truly master the process of analyzing ArrayLists for distinct and recurring values. Add this vital skill to your toolkit!
Java Program:
package TestAutomationCentral;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class FindDuplicateArrayList {
public static void main(String[] args) {
//TestAutomationCentral.com
//Java Program to find Unique and Duplicate Elements in an ArrayList
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(1);
list.add(2);
System.out.println(list);
findUniqueAndDuplicateElements(list);
}
public static void findUniqueAndDuplicateElements(ArrayList<Integer> list){
HashSet<Integer> unique = new HashSet<>();
HashSet<Integer> duplicates = new HashSet<>();
for(Integer value : list){
if(!unique.add(value)){
duplicates.add(value);
}
}
System.out.println("Unique Elements in ArrayList: " + unique);
System.out.println("Duplicate Elements in ArrayList: " + duplicates);
}
}