How to convert a List to a Set in Java

Since both Set and List extend the Collection interface, the conversion is simple. All you need to do is pass a list to a set constructor while initializing or vice versa:

// convert list to set
Set set = new HashSet(list);

// convert set to list
List list = new ArrayList(set);

Convert a List to a Set in Java

Apart from constructor initialization, we can also use Java 8 Streams for a list to a set conversion:

// create a list
List<String> list = new ArrayList<>(Arrays.asList("🐭", "🐧", "🦅", "🐦", "🐭"));

// 1st method - constructor initialization
Set<String> set = new HashSet<>(list);

// 2nd method - using `set.addAll()`
Set<String> set2 = new HashSet<>();
set2.addAll(list);

// 3rd method - using Java 8 Streams
Set<String> set3 = list.stream().collect(Collectors.toSet());

// print values
for (String str : set3) {
    System.out.println(str);
}
// 🐧
// 🐦
// 🐭
// 🦅

Since set collection only allows unique values, all duplicate values from the list will be removed.

Convert a Set to a List in Java

// create a set
Set<String> set = new HashSet<>(Arrays.asList("🐭", "🐧", "🦅", "🐦", "🐭"));

// 1st method - constructor initialization
List<String> list = new ArrayList<>(set);

// 2nd method - using `set.addAll()`
List<String> list2 = new ArrayList<>();
list2.addAll(list);

// 3rd method = using Java 8 Streams
List<String> list3 = set.stream().collect(Collectors.toList());

// print values
for (String str : list3) {
    System.out.println(str);
}
// 🐧
// 🐦
// 🐭
// 🦅

Notice the output. When we first initialized the set, it removed all duplicate values and only kept unique strings.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.