Convert Map to an Array in Java

In this post, we will see how to convert Map to an Array in Java.


 

1. Map to Array of Map.Entry<K,V>

We can easily get an object array of Map.Entry<K,V> using Map.entrySet() + Set.toArray() as shown below:

 

Download   Run Code

Output:

[RED=#FF0000, BLUE=#0000FF]

 

2. Map to Array of keys

We can get an array of keys of the Map using Map.keySet() + Set.toArray(T[] a).

 

Download   Run Code

Output:

[RED, BLUE]

 

3. Map to Array of values

We can get an array of values of the Map using Map.values() + Collection.toArray(T[] a).

 

Download   Run Code

Output:

[#FF0000, #0000FF]

 

4. Map to Array of key-value pairs

We have seen that we can get an array of keys and values of the Map using Map.keySet() and Map.values() respectively. We can easily construct an array of key-value pairs from key[] and value[].

We have used LinkedHashMap in below program that maintains insertion-order iteration, which is the order in which keys were inserted into the map.

 

Download   Run Code

Output:

{1=one}
{2=two}
{12=twelve}
{11=eleven}

This seems pretty straightforward but if HashMap or TreeMap is used, the ordering of both arrays might change i.e. for any index i, there is no guarantee that key[i] will represents the original key for value[i]. To be on safer side, we can construct key[] and value[] as follow:

 

Download   Run Code

Output:

{11=eleven}
{1=one}
{12=twelve}
{2=two}

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz