Hi, I need to convert a HashMap<String, Object>
to an array; could anyone show me how it's done?
views:
6030answers:
3
+12
A:
hashMap.keySet().toArray(); // returns an array of keys
hashMap.values().toArray(); // returns an array of values
landon9720
2009-07-07 05:47:14
beat me to it :(
Here Be Wolves
2009-07-07 05:48:17
gotta get the low hanging fruit where i can find it. :)
landon9720
2009-07-07 05:49:16
+9
A:
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
2009-07-07 06:05:56
A:
Map map = new HashMap(); map.put("key1", "value1"); map.put("key2", "value2");
Object[][] twoDarray = new String[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];
}
for (int i = 0; i < twoDarray.length; i++) {
for (int j = 0; j < twoDarray[i].length; j++) {
System.out.println(twoDarray[i][j]);
}
}
valerian
2010-09-16 12:55:45