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
Can we convert a List to Set and back in Java?
Yes, Java allows easy conversion between List and Set using their constructors. Converting a List to a Set eliminates duplicate entries, and converting a Set back to a List gives a list with only unique values.
List to Set
Pass the list to the HashSet constructor. Duplicates are automatically removed −
Set<Integer> set = new HashSet<>(list);
Set to List
Pass the set to the ArrayList constructor to get a modifiable list −
List<Integer> list = new ArrayList<>(set);
Example
The following example demonstrates converting a List to a Set and back ?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CollectionsDemo {
public static void main(String[] args) {
// List with duplicates
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 3, 3, 4, 5));
System.out.println("Original List: " + list);
// List to Set (duplicates removed)
Set<Integer> set = new HashSet<>(list);
System.out.println("Set: " + set);
// Set back to List (unique values only)
List<Integer> uniqueList = new ArrayList<>(set);
System.out.println("List from Set: " + uniqueList);
}
}
The output of the above code is ?
Original List: [1, 2, 3, 3, 3, 4, 5] Set: [1, 2, 3, 4, 5] List from Set: [1, 2, 3, 4, 5]
The original list had three copies of the value 3. After converting to a Set and back, the resulting list contains only unique values.
Conclusion
Use new HashSet<>(list) for List-to-Set conversion and new ArrayList<>(set) for Set-to-List conversion. This is a common technique for removing duplicates from a list. Note that HashSet does not preserve insertion order; use LinkedHashSet if order needs to be maintained.
