I want to convert hashMap (String,Integer) such as String[], Integer[].
But I heard the information about hashmap.keyset().array() and hashmap.values().array() doesn't match, so it is dangerous,
then, is it possible?
for(Map.Entry<String,Integer> val: hashmap.entrySet()) {
int n = 0;
String key[n]=val.getKey();
int value[n]=val.getValue();
n ;
}
CodePudding user response:
If you want to convert it to a single array then:
Object[] array = hashmap.entrySet().toArray();
or
Map.Entry<String, Integer>[] array =
hashmap.entrySet().toArray(Map.Entry<?, ?>[0]);
(Possibly an unchecked conversion is required, but it is safe ...).
If you want parallel arrays for the keys and values:
String[] keys = new String[hashmap.size()];
Integer[] values = new Integer[hashmap.size()];
int i = 0;
for (e: hashmap.entrySet()) {
keys[i] = e.getKey();
values[i] = e.getValue();
i ;
}
There is probably a neater solution using the Java 8 stream functionality.