Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 956
Evorlor Avatar asked Jun 09 '26 22:06

Evorlor


1 Answers

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()]));
like image 165
Makoto Avatar answered Jun 12 '26 13:06

Makoto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!