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

随声附和 提交于 2021-02-19 06:34:26

问题


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

回答1:


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.




回答2:


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[]


来源:https://stackoverflow.com/questions/53667524/how-to-convert-collectionsetstring-into-string-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!