I need to convert a HashMap<String, Object> to an array; could anyone show me how it's done?
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
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 are using Java 8+ and need a 2 dimensional Array, perhaps for TestNG data providers, you can try:
map.entrySet()
.stream()
.map(e -> new Object[]{e.getKey(), e.getValue()})
.toArray(Object[][]::new);
If your Objects are Strings and you need a String[][], try:
map.entrySet()
.stream()
.map(e -> new String[]{e.getKey(), e.getValue().toString()})
.toArray(String[][]::new);
In the case keys and values are strings and you want to alternate key and value in the same array:
String[] result = myMap.entrySet()
.stream()
.flatMap(entry -> Stream.of(entry.getKey(),entry.getValue()))
.toArray(String[]::new);
// result = {key_1, value_1, key_2, value_2 ...}
You may try this too.
public static String[][] getArrayFromHash(Hashtable<String,String> data){
String[][] str = null;
{
Object[] keys = data.keySet().toArray();
Object[] values = data.values().toArray();
str = new String[keys.length][values.length];
for(int i=0;i<keys.length;i++) {
str[0][i] = (String)keys[i];
str[1][i] = (String)values[i];
}
}
return str;
}
Here I am using String as return type. You may change it to required return type by you.
if you need to pass values to an array of objects try:
Array:
Object[] object= hashMap.values().toArray(new Object[0]);
Arraylist:
ArrayList<Object> object=new ArrayList<>(hashMap.values());