1

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++;
        }
3
  • you can use stream on hashmap.entrySet() Commented Nov 28, 2021 at 6:13
  • Why do you want to do this? The pattern you mention is called parallel arrays, and it is usually better to go to effort not to do that in the first place. Commented Nov 28, 2021 at 6:42
  • Now I am making an application which counts the number of user's watching record and put it order by genre, so i need each array and put it in chart Commented Nov 28, 2021 at 6:54

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.