How to convert a Map to an Array in Java

This tutorial is about several approaches to converting Java’s Map interface implementations into the Java array.

Introduction

In order to turn Java Map to array, it always depend what you actually want to take from the Map itself. You can only want keys or values or transform key-value pairs on a completely different object while turning them into an array.

Note

We need to note, that in most of our examples we will use HashMap implementation as underlying layer upon which the algorithms are build. If the implementation change and it will affect the algorithm, it will be notably depicted and described.

Map Map.Entry to Array

Our first approach is the simplest and probably covers most of the cases in real life. The approach obtains Map.Entry from Map and then turn the collection to an array.

We will use non-parametrized call of Set.toArray() for Entry collection. Let’s look at the example below:

// Method to convert Map entry set into an Array in Java
public static void entrySetToArray()
{
    final Map map = new HashMap<>();

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Gets the Map entry set and turns it into an Array of Objects
    final Object[] objectArray = map.entrySet().toArray();

    System.out.println(Arrays.toString(objectArray));
}

Output

[Paul Smith=555-400-321, John Doe=555-869-759, Thomas Cook=555-906-941]

Map Keys to Array

Sometimes we want to map Map keys to an array. For this we need to use combination of Map.keySet() for obtaining keys and parametrized call of Set.toArray(T[] a) method for keeping a set of keys. Than we can turn key set to an Array.

// Method to convert Map keys into an Array in Java
public static void keySetToArray()
{
    final Map map = new HashMap<>();<>

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Gets the Map set of keys which is turned to an Array of Strings
    String[] keys = map.keySet().toArray(new String[0]);

    System.out.println(Arrays.toString(keys));
}

Output

[Paul Smith, John Doe, Thomas Cook]

Map Values to Array

Other times, we want to map Map values to an array. For this we need to use combination of Map.values() for obtaining keys and parametrized call of Collection.toArray(T[] a) method for keeping a collection of values. Than we can turn value collection to an Array.

// Method to convert Map values into an Array in Java
public static void valuesCollectionToArray()
{
    final Map map = new HashMap<>();

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Gets the Map collection of values and turn it into the Array of Strings
    String[] values = map.values().toArray(new String[0]);

    System.out.println(Arrays.toString(values));
}

Output

[555-400-321, 555-869-759, 555-906-941]

Map to Array with element order secured

We have seen that we can get an array of keys and values of the Map using Map.keySet() and Map.values(). Using both methods we can keep the individual elements in separate arrays and construct a new array of key-value pairs from them.

However we will need to use different Map interface implementation than HashMap. We have to use LinkedHashMap which can secure the order of elements in the order of their insertion into the Map data structure implementation. In this way, we can create two different arrays, one for keys and the second for values, but we can rest assure that the order of elements in individual arrays will be matching their mutual pair in the Map.

// Method to convert Map elements to an Array in Java
// However, the core of this method lies in the Map's implementation LinkedHashMap
// which maintains the order of inserted elements in the order of their insertion.
public static void useLinkedHashMapElementOrderForArrayConversion()
{
    final Map map = new LinkedHashMap<>();

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Get an array of keys in order of the LinkedHashMap
    final String[] keys = map.keySet().toArray(new String[0]);

    // Get an array of values in order of the LinkedHashMap
    final String[] values = map.values().toArray(new String[0]);

    for (int i = 0; i < map.size(); i++) {
        System.out.println( "[ " + keys[i] + " = " + values[i] + " ]" );
    }
}

Output

[ John Doe = 555-869-759 ]
[ Thomas Cook = 555-906-941 ]
[ Paul Smith = 555-400-321 ]

Map to Array with element order unsecured

Finally, we need to discuss the option when the elements' order is not secured, but we want to use two different arrays for help.

When we look on the algorithm above, it seems a little bit straightforward how to map elements to an array. However, when HashMap or TreeMap implementation of Map is used, the order of element in both arrays might change. For example for any index i, there is no guarantee that key[i] will represents the pairing key for value[i] value. To guarantee the correct pair position we need to construct helping arrays and map the pair position into the same indexes in helping arrays.

// Method to convert Map to an Array in Java
public static void maintainKeySetAndValueCollectionArray()
{
    final Map map = new HashMap<>();

    map.put("John Doe", "555-869-759");
    map.put("Thomas Cook", "555-906-941");
    map.put("Paul Smith", "555-400-321");

    // Temporary array to store map keys
    final String[] keys = new String[map.size()];

    // Temporary array to store map values
    final String[] values = new String[map.size()];

    int i = 0;

    for (Map.Entry entry : map.entrySet()) {
        keys[i] = entry.getKey();
        values[i] = entry.getValue();
        i++;
    }

    for (i = 0; i < map.size(); i++) {
        System.out.println( "[ " + keys[i] + " = " + values[i] + " ]" );
    }
}

Note

i is local variable. We can insert i incrementation into the values[i] if you like concise code. However for more readable code, we recomment the incrementation to place on to the new line.

Also, local i variable is reseted for System.out line printing.

Output

[ Paul Smith = 555-400-321 ]
[ John Doe = 555-869-759 ]
[ Thomas Cook = 555-906-941 ]

Conclusion

This article has shown how to convert Java's Map to an Array by various approaches.

All algorithms are placed in the Java method for quick copy and paste into your projects.

While the first three algorithms (Entry, Keys, Values) will cover most of the real-life scenarios of Map to Array conversion, we have shown two more approaches which give you a space for more transformation and conversion. Plus, last two approaches (Map element order secured, Map element order unsecured) pointing out solutions for element order Map security issues.

As always, you can find all our examples on our GitHub project!

This entry was posted in Language basics and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.