如何转换Collection< Set< String>>到字符串数组

如何转换Collection< Set< String>>到字符串数组

问题描述:

当我尝试进行转换时,我遇到了异常

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

这是我的代码

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

您可以简单地使用

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()]);

可以根据情况进行编译,但是现在您可以清楚地看到集合中的任何地方都没有 Integer 类型.因此,在 runtime 处,将使用指定数组的运行时类型和此集合的大小为分配一个新数组.

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.

这是您案例中的 ArrayStoreException 产生的地方,因为您的集合类型为 Set< String> 而不是 String,因此您现在的类型不匹配.

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.