Collections

Convert List to Set Java example

Convert List to Set Java example shows how to convert List to Set in Java. Example also shows how to convert ArrayList to HashSet and ArrayList to TreeSet.

How to convert List to Set (HashSet)?

Let’s first create a List as given below.

There are several ways using which you can convert List to Set as given below.

1) Convert List to Set using HashSet constructor

You can use HashSet constructor which accepts List as an argument as given below.

2) Convert List to Set using addAll method of HashSet

You can use addAll method of HashSet to add all elements of List to HashSet as given below.

3) Convert List to Set using HashSet constructor

If you are using Apache Commons library, you can use addAll method of CollectionUtils class as given below.

4) Convert List to Set using stream (Java 8)

If you are using Java 8 version, you can use stream as given below.

Output

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 above given method work for converting List to TreeSet as well. Just replace HashSet with TreeSet. For example, below given code will convert ArrayList to TreeSet.

Output

As you can see from the output, the elements are now sorted alphabetically.

Please let us know your views in the comments section below.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.