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

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


hashMap.keySet().toArray(); // returns an array of keyshashMap.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]);