How to convert List to Set in java

Previous
Next

In this post, we will see how to convert List to Set in java.We will convert ArrayList to HashSet.

As HashSet does not allow duplicates, when you convert ArrayList to HashSet, all the duplicates will be discarded.

You can simply use the constructor of HashSet to convert ArrayList to HashSet.

Here is simple example:

When you run above program, you will get below output

=======================
List of Countries:
=======================
India
China
Bhutan
Nepal
India
=======================
Set of Countries:
=======================
Bhutan
China
Nepal
India

Java 8 list of set example

You can use Java 8 Stream API to convert list to set.

Just change line 29 in ListToSetMain.java to above and you will get same output.

List to Set in case of Custom objects

You need to quite careful when you are converting list of custom objects to Set.
Let’s understand with help of simple example:

Create a class named “Country”. We will put object of this class to list and then convert it to list.

Create a class named ListToSetCustomObjectMain as below:

When you run above program, you will get below output:

=======================
List of Countries:
=======================
Country [name=India, population=20000]
Country [name=China, population=30000]
Country [name=Bhutan, population=1000]
Country [name=Nepal, population=3000]
Country [name=India, population=20000]
=======================
Set of Countries:
=======================
Country [name=India, population=20000]
Country [name=Nepal, population=3000]
Country [name=India, population=20000]
Country [name=Bhutan, population=1000]
Country [name=China, population=30000]

As you can see, we have Country [name=India, population=20000] twice in the output but these are duplicate entries but HashSet does not consider it as duplicates.
Do you know why?
Because we did not implement hashcode and equals method in Country class.
Let’s add below methods to Country class.

When you run above program again after adding these two methods. You will get below output:

=======================
List of Countries:
=======================
Country [name=India, population=20000]
Country [name=China, population=30000]
Country [name=Bhutan, population=1000]
Country [name=Nepal, population=3000]
Country [name=India, population=20000]
=======================
Set of Countries:
=======================
Country [name=India, population=20000]
Country [name=Nepal, population=3000]
Country [name=China, population=30000]
Country [name=Bhutan, population=1000]

As you can see, we have only one entry for Country [name=India, population=20000] in Set.

That’s all about converting a Set to list in java.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog