

- 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
How can we convert list to Set in Java?
<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<String> set = new HashSet<>(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 −</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 { public static void main(String[] args) { List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "D")); System.out.println("List: " + list); Set<String> set = new HashSet<>(list); System.out.println("Set: " + set); set = new HashSet<>(); set.addAll(list); System.out.println("Set: " + set); set = new HashSet<>(); set = list.stream().collect(Collectors.toSet()); System.out.println("Set: " + set); } }</pre><h2>Output</h2><p>This will produce the following result −</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>
- Related Questions & Answers
- Can we convert a list to a Set in Java?
- Can we convert a List to Set and back 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 List to Set in Java
- How can we convert a list to the JSON array in Java?
- Can we convert an array to list and back in Java?
- How to convert a Java list to a set?
- Program to convert Set to List in Java
- How can we convert a JSON array to a list using Jackson in Java?
- Convert a List to a Set in Java
- How can we set a border to JCheckBox in Java?
- Java Program to convert a List to a Set
- How can we convert character array to a Reader in Java?
Advertisements