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

330,786

Solution 1

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.

Solution 2

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

Solution 3

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]);

Solution 4

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++;
}

Solution 5

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.

Share:
330,786
burntsugar
Author by

burntsugar

Trainer. Student. Developer. Java, Android, Sushi, CAPSLOCK. Concentrates really hard. Especias Secreto. Melbourne Australia.

Updated on April 22, 2021

Comments

  • burntsugar
    burntsugar about 3 years

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

    • harto
      harto almost 15 years
      you want the keys, the values, or both?
  • CrackerJack9
    CrackerJack9 almost 13 years
    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
  • Jake Wilson
    Jake Wilson over 12 years
    @CrackerJack9 can you explain?
  • Landon Kuhn
    Landon Kuhn over 12 years
    The keys wont correspond to their values across the two arrays.
  • CrackerJack9
    CrackerJack9 over 12 years
    @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....
  • Paul Bellora
    Paul Bellora over 12 years
    I think you mean values() instead of keySet() for an array of SomeObject.
  • Choletski
    Choletski almost 9 years
    the question is about HashMap() but your solution is about Hashtable()... There are some differences between them
  • Aquarius Power
    Aquarius Power over 8 years
    perfect! we get both key and value, with auto types fill in eclipse, long time looking for this, thx!
  • Tobiq
    Tobiq almost 5 years
    @CrackerJack9 No, it works. Unlike the accepted solution, this one maintains the key-value pairs. You get {key, value}[] as opposed to key[], value[]
  • Hamburg is nice
    Hamburg is nice almost 5 years
    @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
  • artburkart
    artburkart about 4 years
    I can attest to the danger of this code snippet. When I wrote it, my terminal reached out and slapped me. Extremely dangerous! Beware!
  • Damola Obaleke
    Damola Obaleke over 2 years
    This seems a better solution