Skip to content

Convert List to Set Java example

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.

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.

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.

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.

4) Using stream (Java 8)

If you are using Java 8 or later version, you can use the 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 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.

Output

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

About the author

Leave a Reply

Your email address will not be published.