Evorlor
Evorlor

Reputation: 7553

How can I convert a HashMap<String, ArrayList<String>> to a HashMap<String, String[]>?

I have a HashMap<String, ArrayList<String>>. I am trying to convert it to a HashMap<String, String[]>.

HashMap<String, ArrayList<String>> arrayListMap = new HashMap<>();
HashMap<String, String[]> arrayMap = new HashMap<>();
for (Map.Entry<String, ArrayList<String>> entry : arrayListMap.entrySet()) {
    arrayMap.put(entry.getKey(), entry.getValue().toArray());
}

However, for entry.getValue().toArray(), my IDE is giving me the error:

Wrong 2nd argument type. Found: 'java.lang.Object[], required 'java.lang.String[]'.

I don't know why, because the arrayListMap specifies that I will be working with Strings.

Why is this not working, and how can I fix it?

Upvotes: 3

Views: 245

Answers (2)

Jeet
Jeet

Reputation: 1046

HashMap<String, ArrayList<String>> arrayListMap = new HashMap<>();
        HashMap<String, String[]> arrayMap = new HashMap<>();
        for (Map.Entry<String, ArrayList<String>> entry : arrayListMap.entrySet()) {
            arrayMap.put(entry.getKey(), entry.getValue().toArray(new String[entry.getValue().size()]));
        }

entry.getValue().toArray() will return object array "object[]"

But need String[].

So need to use the method entry.getValue().toArray(T[] a) that returns T[] //generic arg type

Upvotes: -1

Makoto
Makoto

Reputation: 106390

ArrayList has overloaded the toArray method.

The first form, toArray(), will return an Object[] back. This isn't what you want, since you can't convert an Object[] into a String[].

The second form, toArray(T[] a) will return an array back that is typed with whatever array you pass into it.

You need to use the second form here so that the array is correctly typed.

arrayMap.put(entry.getKey(), entry.getValue()
                                  .toArray(new String[entry.getValue().size()]));

Upvotes: 6

Related Questions