当我尝试转换时,出现异常
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
最佳答案
您尝试做的事情是不可能的。文档中对此进行了明确说明。
toArray
方法被记录为抛出 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
相反,您可以做的是从 map 值创建一个流,flatMap 它! (即折叠嵌套序列)然后收集到一个数组:
map.values() // Collection<Set<String>>
.stream() // Stream<Set<String>>
.flatMap(Collection::stream) // Stream<String>
.toArray(String[]::new); // String[]
关于java - 如何将 Collection<Set<String>> 转换为字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53667524/