convert a hashmap to an array

17,105

Solution 1

See same question here:

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

Solution 2

Hm. Your question is really strange, but here is what you asked:

HashMap<String, String[]> map = new HashMap<String, String[]>();
String[] keys = map.keySet().toArray();
Object[] result = new Object[keys.length*2]; //the array that should hold all the values as requested
for(int i = 0; i < keys.length; i++) {
  result[i] = keys[i]; //put the next key into the array
  result[i+1] = map.get(keys[i]); //put the next String[] in the array, according to the key.
}

But man, for what should you ever need something like this? Whatever you want to do, The chance is over 99% that you don't need to write something like this...

Share:
17,105
tetsuya
Author by

tetsuya

Updated on June 08, 2022

Comments

  • tetsuya
    tetsuya about 2 years

    I have a hashmap like this:

    HashMap<String, String[]> map = new HashMap<String, String[]>();
    

    I want to convert this to an array, say Temp[], containing as first value the key from the hashmap and as second the String[]-array from the map, also as array. Is this possible? How?