

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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?
<p>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.</p><pre class="result notranslate">Set<String> set = new HashSet<>(list);</pre><p>On similar pattern, we can get a list from a set using its constructor.</p><pre class="result notranslate">List<Integer> list = new ArrayList<Integer>(set);</pre><h2>Example</h2><p>Following is the example showing the conversion of list to set and set to list −</p><pre class="demo-code notranslate language-java" data-lang="java">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); } }</pre><h2>Output</h2><p>This will produce the following result −</p><pre class="result notranslate">List: [1, 2, 3, 3, 3, 4, 5] Set: [1, 2, 3, 4, 5] List: [1, 2, 3, 4, 5]</pre>
- Related Questions & Answers
- Can we convert an array to list and back in Java?
- Can we convert a list to a Set in Java?
- How can we convert list to Set in Java?
- Can we convert a Java array to list?
- Can we convert a Java list to array?
- Can we convert a list to an Array in Java?
- Convert a List to a Set in Java
- How can we convert a list to the JSON array in Java?
- Convert List to Set in Java
- How to convert IEnumerable to List and List back to IEnumerable in C#?
- Java Program to convert a List to a Set
- How to convert a Java list to a set?
- Convert a Set into a List in Java
- How can we convert a JSON array to a list using Jackson in Java?
- Program to convert Set to List in Java
Advertisements