How can we convert list to Set in Java?

JavaObject Oriented ProgrammingProgramming

<p>A list can be converted to a set object using Set constructor. The resultant set will eliminate 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>Or we can use set.addAll() method to add all the elements of the list to the set.</p><pre class="result notranslate">set.addAll(list);</pre><p>Using streams as well, we can get a set from a list.</p><pre class="result notranslate">set = list.stream().collect(Collectors.toSet());</pre><h2>Example</h2><p>Following is the example showing the list to set conversion via multiple ways &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; import java.util.stream.Collectors; public class CollectionsDemo { &nbsp; &nbsp;public static void main(String[] args) { &nbsp; &nbsp; &nbsp; List&lt;String&gt; list = new ArrayList&lt;&gt;(Arrays.asList(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;D&quot;)); &nbsp; &nbsp; &nbsp; System.out.println(&quot;List: &quot; + list); &nbsp; &nbsp; &nbsp; Set&lt;String&gt; set = new HashSet&lt;&gt;(list); &nbsp; &nbsp; &nbsp; System.out.println(&quot;Set: &quot; + set); &nbsp; &nbsp; &nbsp; set = new HashSet&lt;&gt;(); &nbsp; &nbsp; &nbsp; set.addAll(list); &nbsp; &nbsp; &nbsp; System.out.println(&quot;Set: &quot; + set); &nbsp; &nbsp; &nbsp; set = new HashSet&lt;&gt;(); &nbsp; &nbsp; &nbsp; set = list.stream().collect(Collectors.toSet()); &nbsp; &nbsp; &nbsp; System.out.println(&quot;Set: &quot; + set); &nbsp; &nbsp;} }</pre><h2>Output</h2><p>This will produce the following result &minus;</p><pre class="result notranslate">List: [A, B, C, D, D] Set: [A, B, C, D] Set: [A, B, C, D] Set: [A, B, C, D]</pre>
raja
Updated on 09-May-2022 12:09:41

Advertisements