136

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

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
burntsugar
  • 57,360
  • 21
  • 58
  • 81

14 Answers14

219
hashMap.keySet().toArray(); // returns an array of keys
hashMap.values().toArray(); // returns an array of values

Edit

It should be noted that the ordering of both arrays may not be the same, See oxbow_lakes answer for a better approach for iteration when the pair key/values are needed.

fwoosh
  • 184
  • 3
  • 15
Landon Kuhn
  • 76,451
  • 45
  • 104
  • 130
  • 10
    Actually, this code offers no guarantee that hashMap.keySet().toArray()[0] will be the original key for hashMap.values().toArray()[0] from the original Map. So this is extremely *dangerous* – CrackerJack9 Aug 07 '11 at 18:20
  • 2
    @CrackerJack9 can you explain? – Jake Wilson Nov 02 '11 at 15:27
  • 13
    The keys wont correspond to their values across the two arrays. – Landon Kuhn Nov 02 '11 at 18:50
  • 5
    @Jakobud landon9720 is correct...the order is psuedo-random, and it cannot be guaranteed that key[0] will correspond to value[0] after you convert the keys to a `Set` and the values to a `Collection`. While they are technically converted to arrays (and answers your question), the concept of the key-value pair has been lost - which is why this is a very misleading (and dangerous) answer.... – CrackerJack9 Nov 03 '11 at 06:43
  • 2
    I can attest to the danger of this code snippet. When I wrote it, my terminal reached out and slapped me. Extremely dangerous! Beware! – artburkart May 03 '20 at 13:28
75

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

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
61

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]);
fwoosh
  • 184
  • 3
  • 15
kmccoy
  • 2,761
  • 3
  • 25
  • 29
  • 3
    I think you mean `values()` instead of `keySet()` for an array of `SomeObject`. – Paul Bellora Feb 08 '12 at 04:33
  • 1
    @Alex "In older Java versions using pre-sized array was recommended (...) However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation." - intellij – Hamburg is nice Sep 14 '19 at 22:46
31

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++;
}
CrackerJack9
  • 3,650
  • 1
  • 27
  • 48
12

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.

Dean Wild
  • 5,886
  • 3
  • 38
  • 45
8

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

hashMap.values().toArray(new MyObject[0]);
Hugo Tavares
  • 314
  • 4
  • 14
7
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]);
    }
}
Graham Russell
  • 997
  • 13
  • 24
valerian
  • 79
  • 1
  • 1
6

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);
Graham Russell
  • 997
  • 13
  • 24
3

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++;
}
Mitul Maheshwari
  • 2,647
  • 4
  • 24
  • 38
3

In the case keys and values are strings and you want to alternate key and value in the same array:

String[] result = myMap.entrySet()
                       .stream()
                       .flatMap(entry -> Stream.of(entry.getKey(),entry.getValue()))
                       .toArray(String[]::new);
// result = {key_1, value_1, key_2, value_2 ...}
0
@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;
    }
Ali Bagheri
  • 3,068
  • 27
  • 28
0
HashMap<String, String> hashMap = new HashMap<>();
String[] stringValues= new String[hashMap.values().size()];
hashMap.values().toArray(stringValues);
Roman Irtov
  • 363
  • 3
  • 12
0

if you need to pass values to an array of objects try:

Array:
Object[] object= hashMap.values().toArray(new Object[0]);

Arraylist:
ArrayList<Object> object=new ArrayList<>(hashMap.values());
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.

Mayur
  • 676
  • 8
  • 16
  • 1
    the question is about `HashMap()` but your solution is about `Hashtable()`... There are some [differences](http://stackoverflow.com/a/40878/3595288) between them – Choletski Aug 24 '15 at 11:55