Since both Set and List extend the Collection interface, the conversion is simple. All you need to do is just pass a list to 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);

List to Set Conversion

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.

Set to List Conversion

// 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 @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. β˜• Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.