[java] Java: how to convert HashMap<String, Object> to array

I need to convert a HashMap<String, Object> to an array; could anyone show me how it's done?

This question is related to java arrays collections hashmap

The answer is


Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");

Object[][] twoDarray = new Object[map.size()][2];

Object[] keys = map.keySet().toArray();
Object[] values = map.values().toArray();

for (int row = 0; row < twoDarray.length; row++) {
    twoDarray[row][0] = keys[row];
    twoDarray[row][1] = values[row];
}

// Print out the new 2D array
for (int i = 0; i < twoDarray.length; i++) {
    for (int j = 0; j < twoDarray[i].length; j++) {
        System.out.println(twoDarray[i][j]);
    }
}

HashMap<String, String> hashMap = new HashMap<>();
String[] stringValues= new String[hashMap.values().size()];
hashMap.values().toArray(stringValues);

If you want the keys and values, you can always do this via the entrySet:

hashMap.entrySet().toArray(); // returns a Map.Entry<K,V>[]

From each entry you can (of course) get both the key and value via the getKey and getValue methods


@SuppressWarnings("unchecked")
    public static <E,T> E[] hashMapKeysToArray(HashMap<E,T> map)
    {
        int s;
        if(map == null || (s = map.size())<1)
            return null;

        E[] temp;
        E typeHelper;
        try
        {
            Iterator<Entry<E, T>> iterator = map.entrySet().iterator();
            Entry<E, T> iK = iterator.next();
            typeHelper = iK.getKey();

            Object o = Array.newInstance(typeHelper.getClass(), s);
            temp = (E[]) o;

            int index = 0;
            for (Map.Entry<E,T> mapEntry : map.entrySet())
            {
                temp[index++] = mapEntry.getKey();
            }
        }
        catch (Exception e)
        {
            return null;
        }
        return temp;
    }
//--------------------------------------------------------
    @SuppressWarnings("unchecked")
    public static <E,T> T[] hashMapValuesToArray(HashMap<E,T> map)
    {
        int s;
        if(map == null || (s = map.size())<1)
            return null;

        T[] temp;
        T typeHelper;
        try
        {
            Iterator<Entry<E, T>> iterator = map.entrySet().iterator();
            Entry<E, T> iK = iterator.next();
            typeHelper = iK.getValue();

            Object o = Array.newInstance(typeHelper.getClass(), s);
            temp = (T[]) o;

            int index = 0;
            for (Map.Entry<E,T> mapEntry : map.entrySet())
            {
                temp[index++] = mapEntry.getValue();
            }
        }
        catch (Exception e)
        {return null;}

        return temp;
    }

To guarantee the correct order for each array of Keys and Values, use this (the other answers use individual Sets which offer no guarantee as to order.

Map<String, Object> map = new HashMap<String, Object>();
String[] keys = new String[map.size()];
Object[] values = new Object[map.size()];
int index = 0;
for (Map.Entry<String, Object> mapEntry : map.entrySet()) {
    keys[index] = mapEntry.getKey();
    values[index] = mapEntry.getValue();
    index++;
}

An alternative to CrackerJacks suggestion, if you want the HashMap to maintain order you could consider using a LinkedHashMap instead. As far as im aware it's functionality is identical to a HashMap but it is FIFO so it maintains the order in which items were added.


If you have HashMap<String, SomeObject> hashMap then:

hashMap.values().toArray();

Will return an Object[]. If instead you want an array of the type SomeObject, you could use:

hashMap.values().toArray(new SomeObject[0]);

You may try this too.

public static String[][] getArrayFromHash(Hashtable<String,String> data){
        String[][] str = null;
        {
            Object[] keys = data.keySet().toArray();
            Object[] values = data.values().toArray();
            str = new String[keys.length][values.length];
            for(int i=0;i<keys.length;i++) {
                str[0][i] = (String)keys[i];
                str[1][i] = (String)values[i];
            }
        }
        return str;
    }

Here I am using String as return type. You may change it to required return type by you.


I used almost the same as @kmccoy, but instead of a keySet() I did this

hashMap.values().toArray(new MyObject[0]);

If you are using Java 8+ and need a 2 dimensional Array, perhaps for TestNG data providers, you can try:

map.entrySet()
    .stream()
    .map(e -> new Object[]{e.getKey(), e.getValue()})
    .toArray(Object[][]::new);

If your Objects are Strings and you need a String[][], try:

map.entrySet()
    .stream()
    .map(e -> new String[]{e.getKey(), e.getValue().toString()})
    .toArray(String[][]::new);

To Get in One Dimension Array.

    String[] arr1 = new String[hashmap.size()];
    String[] arr2 = new String[hashmap.size()];
    Set entries = hashmap.entrySet();
    Iterator entriesIterator = entries.iterator();

    int i = 0;
    while(entriesIterator.hasNext()){

        Map.Entry mapping = (Map.Entry) entriesIterator.next();

        arr1[i] = mapping.getKey().toString();
        arr2[i] = mapping.getValue().toString();

        i++;
    }


To Get in two Dimension Array.

   String[][] arr = new String[hashmap.size()][2];
   Set entries = hashmap.entrySet();
   Iterator entriesIterator = entries.iterator();

   int i = 0;
   while(entriesIterator.hasNext()){

    Map.Entry mapping = (Map.Entry) entriesIterator.next();

    arr[i][0] = mapping.getKey().toString();
    arr[i][1] = mapping.getValue().toString();

    i++;
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to hashmap

How to split a string in two and store it in a field Printing a java map Map<String, Object> - How? Hashmap with Streams in Java 8 Streams to collect value of Map How to convert String into Hashmap in java Convert object array to hash map, indexed by an attribute value of the Object HashMap - getting First Key value The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files Sort Go map values by keys Print all key/value pairs in a Java ConcurrentHashMap creating Hashmap from a JSON String