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 to convert a Java list to a set?
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<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 3, 3, 4, 5));
System.out.println("List: " + list);
// Method 1: Constructor
Set<Integer> set1 = new HashSet<>(list);
System.out.println("Set (constructor): " + set1);
// Method 2: addAll()
Set<Integer> set2 = new HashSet<>();
set2.addAll(list);
System.out.println("Set (addAll): " + set2);
// Method 3: Streams
Set<Integer> set3 = list.stream().collect(Collectors.toSet());
System.out.println("Set (stream): " + set3);
}
}
The output of the above code is ?
List: [1, 2, 3, 3, 3, 4, 5] Set (constructor): [1, 2, 3, 4, 5] Set (addAll): [1, 2, 3, 4, 5] Set (stream): [1, 2, 3, 4, 5]
Conclusion
All three methods produce the same result − duplicates are removed and only unique values remain. The constructor approach is the most concise, while the Stream approach offers more flexibility for additional transformations before collecting into a Set.
