Convert List to Set Java example shows how to convert List to Set in Java. The example also shows how to convert ArrayList to HashSet and ArrayList to TreeSet.
The List and Set interfaces are part of the Java Collection framework.
How to convert List to Set (HashSet)?
Let’s first create a List object and add elements as given below.
1 2 3 4 5 6 |
List<String> listColors = new ArrayList<String>(); listColors.add("Red"); listColors.add("Blue"); listColors.add("White"); listColors.add("Green"); listColors.add("Yellow"); |
There are several ways using which we can do the conversion as given below.
1) Using HashSet constructor
You can use the HashSet constructor which accepts a List as an argument as given below.
1 2 3 |
Set<String> setColors = new HashSet<String>( listColors ); System.out.println(setColors); |
2) Using the addAll method of HashSet
You can use the addAll
method of the HashSet class to add all elements of the List to HashSet as given below.
1 2 3 4 |
Set<String> setColors = new HashSet<String>(); setColors.addAll(listColors); System.out.println(setColors); |
3) Using Apache Commons
If you are using the Apache Commons library, you can use the addAll
method of the CollectionUtils class as given below.
1 2 3 4 |
Set<String> setColors = new HashSet<String>(); CollectionUtils.addAll(setColors, listColors); System.out.println(setColors); |
4) Using stream (Java 8)
If you are using Java 8 or later version, you can use the stream as given below.
1 2 3 |
Set<String> setColors = listColors.stream().collect(Collectors.toSet()); System.out.println(setColors); |
Output
1 |
[Red, White, Blue, Yellow, Green] |
Converting List to HashSet does not sort the elements of the list. If you want a sorted Set, you can convert List to TreeSet which will sort the List elements as given below.
How to convert List to TreeSet (convert ArrayList to TreeSet)?
All the above given methods work for converting a List to TreeSet as well. Just replace the HashSet with TreeSet. For example, below given code will convert ArrayList to TreeSet.
1 2 3 4 5 6 7 8 9 10 11 |
List<String> listColors = new ArrayList<String>(); listColors.add("Red"); listColors.add("Blue"); listColors.add("White"); listColors.add("Green"); listColors.add("Yellow"); //convert ArrayList to TreeSet Set<String> setColors = new TreeSet<String>( listColors ); System.out.println(setColors); |
Output
1 |
[Blue, Green, Red, White, Yellow] |
The TreeSet is a sorted collection, so the elements are now sorted alphabetically.
This example is a part of the Java ArrayList tutorial and Java TreeSet tutorial.
Please let me know your views in the comments section belo