java - 如何将 Collection<Set<String>> 转换为字符串数组

标签 java collections

当我尝试转换时,出现异常

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/

相关文章:

python - 如何在没有引用对象实例的情况下获取集合名称?

java.util.Set、java.util.List 可序列化问题

java - 如何查询按计数分组的对象列表(按最后一天的提及频率)

java - 使用 DriverManager.getConnection() 找不到符号

java - JGAP 不保留适者生存

collections - Drools 规则检查具有复合值限制的集合

java - 为什么 Hashmap 允许空键?

iphone - 从 NSDictionary 实例化自定义类

java - JmsTemplate 中的空指针异常?

java - 部署 Spring Boot 应用程序时 Heroku 错误代码 H10