Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can we convert list to Set in Java?
A Java List can be converted to a Set to eliminate duplicate entries. The resulting Set will contain only unique values. There are three common ways to perform this conversion −
Method 1: Using Set Constructor
Pass the list directly to the HashSet constructor −
Set<String> set = new HashSet<>(list);
Method 2: Using addAll()
Create an empty set and use addAll() to add all elements from the list −
Set<String> set = new HashSet<>(); set.addAll(list);
Method 3: Using Streams (Java 8+)
Use the Stream API to collect list elements into a set −
Set<String> set = list.stream().collect(Collectors.toSet());
Example
The following example demonstrates all three approaches ?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "D"));
System.out.println("List: " + list);
// Method 1: Constructor
Set<String> set1 = new HashSet<>(list);
System.out.println("Set (constructor): " + set1);
// Method 2: addAll()
Set<String> set2 = new HashSet<>();
set2.addAll(list);
System.out.println("Set (addAll): " + set2);
// Method 3: Streams
Set<String> set3 = list.stream().collect(Collectors.toSet());
System.out.println("Set (stream): " + set3);
}
}
The output of the above code is ?
List: [A, B, C, D, D] Set (constructor): [A, B, C, D] Set (addAll): [A, B, C, D] Set (stream): [A, B, C, D]
The duplicate "D" in the list is automatically removed during conversion since a Set does not allow duplicate elements.
Conclusion
All three methods produce the same result. The constructor approach is the most concise, while the Stream approach offers flexibility for additional transformations. Use LinkedHashSet instead of HashSet if you need to preserve the insertion order from the original list.
