如何转换Collection< Set< String>>到字符串数组 [英] How to convert Collection<Set<String>> into String Array

查看:96
本文介绍了如何转换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.

这篇关于如何转换Collection&lt; Set&lt; String&gt;&gt;到字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆