1. Introduction
In Java, a List can contain duplicate elements. There are several ways to remove duplicates from a List, one common way is by using a Set. A Set is a Collection that does not allow duplicate elements. In this tutorial, we will demonstrate how to remove duplicate elements from a List using a Set.
2. Program Steps
1. Import the necessary classes.
2. Create a List with some duplicate elements.
3. Convert the List to a Set to remove the duplicate elements.
4. Convert the Set back to a List.
5. Print the original and the modified List.
3. Code Program
// Step 1: Importing necessary classes
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RemoveDuplicates {
public static void main(String[] args) {
// Step 2: Creating a List with some duplicate elements
List<String> listWithDuplicates = new ArrayList<>();
listWithDuplicates.add("Apple");
listWithDuplicates.add("Banana");
listWithDuplicates.add("Cherry");
listWithDuplicates.add("Apple");
listWithDuplicates.add("Banana");
// Printing the original list
System.out.println("Original List: " + listWithDuplicates);
// Step 3: Converting the List to a Set to remove the duplicate elements
Set<String> setWithoutDuplicates = new HashSet<>(listWithDuplicates);
// Step 4: Converting the Set back to a List
List<String> listWithoutDuplicates = new ArrayList<>(setWithoutDuplicates);
// Printing the modified list
System.out.println("List Without Duplicates: " + listWithoutDuplicates);
}
}
Output:
Original List: [Apple, Banana, Cherry, Apple, Banana] List Without Duplicates: [Banana, Cherry, Apple]
4. Step By Step Explanation
Step 1: Import the necessary classes. In this case, we import ArrayList, HashSet, List, and Set.
Step 2: Create a List named listWithDuplicates and add some elements to it, including duplicates.
Step 3: Create a Set named setWithoutDuplicates and initialize it with the elements of listWithDuplicates. Since a Set does not allow duplicate elements, this will effectively remove any duplicates from the List.
Step 4: Convert setWithoutDuplicates back to a List named listWithoutDuplicates.
Finally, print the original listWithDuplicates and the listWithoutDuplicates to observe the removal of duplicate elements.