views:

6030

answers:

3

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

+12  A: 
 hashMap.keySet().toArray(); // returns an array of keys
 hashMap.values().toArray(); // returns an array of values
landon9720
beat me to it :(
Here Be Wolves
gotta get the low hanging fruit where i can find it. :)
landon9720
+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
+1 that's exactly what I was looking for!
KennyCason
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