Reputation: 623
I have a HashMap which I want to convert into a array. Which the code below, I get following: [[2, 11, 10, 9], [value1, value2, value3, value4], [null, null, null, null], [null, null, null, null]] The "null" entries give me a null pointer exception. Why is it two times as big as it should be? I just want the real entries: [[2, 11, 10, 9], [value1, value2, value3, value4]]. What did I wrong?
String[][] test = getArrayFromHash(hashmap);
public static String[][] getArrayFromHash(HashMap<String, String> hashMap){
String[][] str = null;
{
Object[] keys = hashMap.keySet().toArray();
Object[] values = hashMap.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;
}
Thanks!
Upvotes: 3
Views: 6968
Reputation: 34775
Refer this link:::
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++;
}
UPdated:::: to get two 1D arrays
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++;
}
Upvotes: 4
Reputation: 807
I'm not sure if keyset and values will necessary return the values in the same order (it's not specified in the implementation doc so I'd say it's not guaranteed).
try working with entrysets:
Set<Map.Entry<String, String>> set = hm.entrySet();
int i = 0;
for (Map.Entry<String,String> me : set) {
arr[i][0] = me.getKey();
arr[i][1] = me.getValue()};
i++;
}
Upvotes: 3
Reputation: 46492
Allocate array of proper size like
str = new String[2][values.length];
Moreover you should assert that values and keys have the same length. And also that matching entries appear at the same position. Something like
String[] keys = hashMap.keySet().toArray(new String[0]);
String[] values = new String[keys.length];
String[][] str = {keys, values};
for(int i=0;i<keys.length;i++) values[i] = hashMap.get(keys[i]);
return str;
should do (not tested).
Upvotes: 3