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.