Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you convert the values of a HashMap to an array?

One way to convert is to use the constructor of the ArrayList. In order to do this, we can use the keySet() method present in the HashMap. This method returns the set containing all the keys of the hashmap.

How do I convert a String array to an array in Java?

String class split(String regex) can be used to convert String to array in java. If you are working with java regular expression, you can also use Pattern class split(String regex) method.


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

To guarantee the correct order for each array of Keys and Values, use this (the other answers use individual Sets which offer no guarantee as to order.

Map<String, Object> map = new HashMap<String, Object>();
String[] keys = new String[map.size()];
Object[] values = new Object[map.size()];
int index = 0;
for (Map.Entry<String, Object> mapEntry : map.entrySet()) {
    keys[index] = mapEntry.getKey();
    values[index] = mapEntry.getValue();
    index++;
}

An alternative to CrackerJacks suggestion, if you want the HashMap to maintain order you could consider using a LinkedHashMap instead. As far as im aware it's functionality is identical to a HashMap but it is FIFO so it maintains the order in which items were added.


I used almost the same as @kmccoy, but instead of a keySet() I did this

hashMap.values().toArray(new MyObject[0]);