Can we convert a List to Set and back in Java?

JavaObject Oriented ProgrammingProgramming

<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&lt;String&gt; set = new HashSet&lt;&gt;(list);</pre><p>On similar pattern, we can get a list from a set using its constructor.</p><pre class="result notranslate">List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;(set);</pre><h2>Example</h2><p>Following is the example showing the conversion of list to set and set to list &minus;</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 { &nbsp; &nbsp;public static void main(String[] args) { &nbsp; &nbsp; &nbsp; List&lt;Integer&gt; list = new ArrayList&lt;&gt;(Arrays.asList(1,2,3,3,3,4,5)); &nbsp; &nbsp; &nbsp; System.out.println(&quot;List: &quot; + list); &nbsp; &nbsp; &nbsp; Set&lt;Integer&gt; set = new HashSet&lt;&gt;(list); &nbsp; &nbsp; &nbsp; System.out.println(&quot;Set: &quot; + set); &nbsp; &nbsp; &nbsp; List&lt;Integer&gt; list1 = new ArrayList&lt;Integer&gt;(set); &nbsp; &nbsp; &nbsp; System.out.println(&quot;List: &quot; + list1); &nbsp; &nbsp;} }</pre><h2>Output</h2><p>This will produce the following result &minus;</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>
Updated on 09-May-2022 12:06:15