nahi Aata
nahi Aata

Reputation: 117

How to convert Collection<Set<String>> into String Array

When I am trying to convert, I am getting below exception

java.lang.ArrayStoreException: java.util.HashSet
        at java.util.AbstractCollection.toArray(Unknown Source)

This is my code

Map<String, Set<String>> map = new HashMap<>();
String[] keySet = map.keySet().toArray(new String[map.size()]);
Collection<Set<String>> collections = map.values();
String[] values = collection.toArray(new String[collection.size()]);// In this line getting Exception

Upvotes: 2

Views: 1627

Answers (2)

Naman
Naman

Reputation: 31868

You can simply use Stream.flatMap as you stream over the values to collect them later into an array. This can be done as:

String[] values = map.values().stream()
                  .flatMap(Collection::stream)
                  .toArray(String[]::new);

Note: The reason why your code compiles successfully even with

toArray(new String[collection.size()])

is that Collection.toArray(T[] a) because its hard for the compiler to determine the type prior to execution for a generic type. This is the same reason why even

Integer[] values = collections.toArray(new Integer[collections.size()]);

would compile in your case, but as you can now clearly see that nowhere in your collections do you have an Integer type. Hence at runtime, a new array is allocated with the runtime type of the specified array and the size of this collection.

That is where the ArrayStoreException in your case results from since now you have a type mismatch as your collection is of type Set<String> instead of String.

Important: You cannot possibly convert to a generic array as you may further think of.

Upvotes: 2

Ousmane D.
Ousmane D.

Reputation: 56423

What you're attempting to do is not possible. This is made explicit in the documentation.

The toArray method is documented to throw a java.lang.ArrayStoreException:

if the runtime type of the specified array is not a supertype of the runtime type of every element in this collection

instead, what you can do is create a stream from the map values, flatMap it! (i.e. collapse the nested sequences) then collect to an array:

 map.values()  // Collection<Set<String>>
    .stream()  // Stream<Set<String>>
    .flatMap(Collection::stream) // Stream<String>
    .toArray(String[]::new); // String[]

Upvotes: 3

Related Questions