- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we convert a List to Set and back in Java?
A list can be converted to a set object using Set constructor. The resultant set will elliminate any duplicate entry present in the list and will contains only the unique values.
Set<String> set = new HashSet<>(list);
On similar pattern, we can get a list from a set using its constructor.
List<Integer> list = new ArrayList<Integer>(set);
Example
Following is the example showing the conversion of list to set and set to list −
package com.tutorialspoint; 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<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,3,3,4,5)); System.out.println("List: " + list); Set<Integer> set = new HashSet<>(list); System.out.println("Set: " + set); List<Integer> list1 = new ArrayList<Integer>(set); System.out.println("List: " + list1); } }
Output
This will produce the following result −
List: [1, 2, 3, 3, 3, 4, 5] Set: [1, 2, 3, 4, 5] List: [1, 2, 3, 4, 5]
Advertisements