- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 do you turn a list into a Set in Java?
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, 4, 4)); 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, 4, 4] Set: [1, 2, 3, 4] Set: [1, 2, 3, 4] Set: [1, 2, 3, 4]
- Related Articles
- How do you turn an ArrayList into a Set in Java?
- How do I turn a list into an array in Java?
- How do you create a list from a set in Java?
- How do you copy a list in Java?
- How do you create a list in Java?
- Convert a Set into a List in Java
- How do you make a list iterator in Java?
- How do you convert a list collection into an array in C#?
- How do you split a list into evenly sized chunks in Python?
- How do you create a list with values in Java?
- How do you make a shallow copy of a list in Java?
- How do you add an element to a list in Java?
- How do you check a list contains an item in Java?
- How do I set the size of a list in Java?
- How do you convert list to array in Java?

Advertisements