

- 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 to convert a Java list to a set?
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);
Or we can use set.addAll() method to add all the elements of the list to the set.
set.addAll(list);
Using streams as well, we can get a set from a list.
set = list.stream().collect(Collectors.toSet());
Example
Following is the example showing the list to set conversion via multiple ways −
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<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); 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); } }
Output
This will produce the following result −
List: [1, 2, 3, 3, 3, 4, 5] Set: [1, 2, 3, 4, 5] Set: [1, 2, 3, 4, 5] Set: [1, 2, 3, 4, 5]
- Related Questions & Answers
- Convert a List to a Set in Java
- Java Program to convert a List to a Set
- Can we convert a list to a Set in Java?
- Convert a Set into a List in Java
- Convert List to Set in Java
- Program to convert Set to List in Java
- How can we convert list to Set in Java?
- Can we convert a List to Set and back in Java?
- What is the easiest way to convert a List to a Set in Java?
- How to convert a list to array in Java?
- Java Program to convert a list to a read-only list
- Convert a Queue to a List in Java
- How to convert an Array to a Set in Java?
- How to convert an array to a list in Java?
- How to convert a list collection into a dictionary in Java?
Advertisements