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?


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

Edit

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

链接地址: http://www.djcxy.com/p/16358.html

上一篇: 字典和哈希表之间的区别

下一篇: Java:如何将HashMap <String,Object>转换为数组