I need to convert a HashMap
to an array; could anyone show me how it\'s done?
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.
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.
HashMap<String, String> hashMap = new HashMap<>();
String[] stringValues= new String[hashMap.values().size()];
hashMap.values().toArray(stringValues);
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
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
Object[][] twoDarray = new Object[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];
}
// Print out the new 2D array
for (int i = 0; i < twoDarray.length; i++) {
for (int j = 0; j < twoDarray[i].length; j++) {
System.out.println(twoDarray[i][j]);
}
}
To Get in One Dimension Array.
String[] arr1 = new String[hashmap.size()];
String[] arr2 = new String[hashmap.size()];
Set entries = hashmap.entrySet();
Iterator entriesIterator = entries.iterator();
int i = 0;
while(entriesIterator.hasNext()){
Map.Entry mapping = (Map.Entry) entriesIterator.next();
arr1[i] = mapping.getKey().toString();
arr2[i] = mapping.getValue().toString();
i++;
}
To Get in two Dimension Array.
String[][] arr = new String[hashmap.size()][2];
Set entries = hashmap.entrySet();
Iterator entriesIterator = entries.iterator();
int i = 0;
while(entriesIterator.hasNext()){
Map.Entry mapping = (Map.Entry) entriesIterator.next();
arr[i][0] = mapping.getKey().toString();
arr[i][1] = mapping.getValue().toString();
i++;
}