Java: how to convert HashMap<String, Object> to array
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.
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
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]);
To guarantee the correct order for each array of Keys and Values, use this (the other answers use individual Set
s 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.