Java Program To Remove Duplicate Elements From List
Chapter:
Miscellaneous
Last Updated:
07-10-2023 07:01:17 UTC
Program:
/* ............... START ............... */
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RemoveDuplicatesFromList {
public static void main(String[] args) {
// Create a list with duplicate elements
List<Integer> listWithDuplicates = new ArrayList<>();
listWithDuplicates.add(1);
listWithDuplicates.add(2);
listWithDuplicates.add(3);
listWithDuplicates.add(2);
listWithDuplicates.add(4);
listWithDuplicates.add(1);
// Create a Set to store unique elements
Set<Integer> uniqueSet = new HashSet<>();
// Iterate through the original list and add elements to the set
// Duplicate elements will automatically be removed
for (Integer element : listWithDuplicates) {
uniqueSet.add(element);
}
// Create a new list to store the unique elements
List<Integer> listWithoutDuplicates = new ArrayList<>(uniqueSet);
// Print the list without duplicates
System.out.println("List with duplicates: " + listWithDuplicates);
System.out.println("List without duplicates: " + listWithoutDuplicates);
}
}
/* ............... END ............... */
Output
List with duplicates: [1, 2, 3, 2, 4, 1]
List without duplicates: [1, 2, 3, 4]
Notes:
-
First we create a list called listWithDuplicates containing some duplicate elements.
- In next step create a HashSet called uniqueSet to store the unique elements from the original list. The HashSet automatically removes duplicates because it doesn't allow duplicate elements.
- Then we iterate through the original list and add each element to the uniqueSet.
- Finally, we create a new list called listWithoutDuplicates and initialize it with the elements from the uniqueSet. This gives us a list without duplicate elements.
- When you run this program, you will see that the list listWithoutDuplicates contains the unique elements from the original list, and duplicates are removed.
Tags
Java program to remove duplicate elements from list #How to remove duplicates from list of list in Java?