This post will discuss how to convert map to an array in Java.

1. Convert Map<K,V> to array of Map.Entry<K,V>

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

Download  Run Code

Output:

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

2. Convert map to array of keys

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

Download  Run Code

Output:

[RED, BLUE]

3. Convert map to array of values

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

Download  Run Code

Output:

[#FF0000, #0000FF]

4. Convert 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 the following 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 represent the original key for value[i]. To be on the safer side, we can construct key[] and value[] as follows:

Download  Run Code

Output:

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

That’s all about converting Map to an array in Java.