JPep26
JPep26

Reputation: 13

how can i convert hashmap to array?

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++;
        }

Upvotes: 1

Views: 693

Answers (1)

Stephen C
Stephen C

Reputation: 719616

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.

Upvotes: 2

Related Questions