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

I have HashMap<String, ArrayList<String>>

. I am trying to convert it to 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 it gives me an error:

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

      

I don't know why, because it arrayListMap

indicates that I will be working with String

s.

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

+3


source to share


2 answers


ArrayList

overloaded the method toArray

.

The first form toArray()

will return it back Object[]

. This is not what you want, as you cannot convert Object[]

to String[]

.

The second form toArray(T[] a)

will return the array back, which is entered with whatever array you pass into it.



You need to use the second form here for the array to print correctly.

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

      

+6


source


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 an array of "object []"



But the line [] is needed.

Therefore, you need to use the entry.getValue () method. toArray (T [] a), which returns T [] // generic type arg

-1


source







All Articles