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.