Convert HashMap to ArrayList in java

In this post, we will see how to convert HashMap to ArrayList in java. Many times, you need to store keys or values into ArrayList or Store HashMap’s Node objects in ArrayList.

HashMap and ArrayList both are the most used data structure in java and both have different Hierarchy.

Here are the ways to convert HashMap to ArrayList in java.

Using Java 8’s Stream API

Java 8: Convert HashMap’s keys to ArrayList

We can use HashMap’s keyset()  method to get a set of keys and use Java 8‘s Stream API to convert it to ArrayList.

Convert HashMap’s values to ArrayList

We can use HashMap’s values() method to get a collection of values and use Java 8’s Stream API to convert it to ArrayList.

Convert HashMap’s Entry objects to ArrayList

We can use HashMap’s entrySet() method to get set of Entry object and use Java 8’s Stream API to convert it to ArrayList.

Let’s see the complete example.

Output:

customerIds: [1001, 1002, 1003, 1004] Customer Names: [Arman, Javin, Mat, Joe] Customer ID and Names: [1001=Arman, 1002=Javin, 1003=Mat, 1004=Joe]

Using ArrayList’s constructor

Convert HashMap’s keys to ArrayList

Get keySet()  from HashMap and then convert it to ArrayList using its constructor.

Convert HashMap’s values to ArrayList

Get values() from HashMap and then convert it to ArrayList using its constructor.

Convert HashMap’s Entry objects to ArrayList

Get entrySet()  from HashMap and then convert it to ArrayList using its constructor.

Here is the complete program to convert HashMap to ArrayList.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *