【问题标题】:How to convert Map<Shape, int[]> to Map<Shape, Set<Integer>> in Java 8?如何在 Java 8 中将 Map<Shape, int[]> 转换为 Map<Shape, Set<Integer>>?
【发布时间】:2018-05-14 13:22:04
【问题描述】:

我是 Java 8 的新手,我有以下转换要求:

Map<Shape, int[]> --> Map<Shape, Set<Integer>>

有什么想法吗?

【问题讨论】:

    标签: java dictionary java-8 set


    【解决方案1】:

    我编辑了这个问题,希望Set&lt;Integer&gt; 是您真正需要的,因为您不能拥有Set&lt;int&gt; 类型的原始Set

     map.entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Entry::getKey,
                        x -> Arrays.stream(x.getValue()).boxed().collect(Collectors.toSet())
    
        ));
    

    另一方面,如果你真的想要独特的原语,那么 distincttoArray 可以工作,但类型仍然是 Map&lt;Shape, int[]&gt;

     map.entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Entry::getKey,
                        x -> Arrays.stream(x.getValue()).distinct().toArray()
    
        ));
    

    【讨论】:

    • 也许可以添加一条评论,告诉您无法获得Set&lt;int&gt;,而只能获得Set&lt;Integer&gt;
    • 在转换地图的同一阶段不能把int[]装箱吗?
    • 谢谢你,你的回答让我找到了正确的解决方案!
    【解决方案2】:

    这是一种将int数组转换为Set&lt;Integer&gt;的方法:

    private Set<Integer> convertArrayToSet(int[] array) {
        return stream(array).boxed().collect(toSet());
    }
    

    你需要通过这个方法跳过map的每个值:

    public Map<Shape, Set<Integer>> convert(Map<Shape, int[]> map) {
        return map.entrySet()
                .stream()
                .collect(toMap(e -> e.getKey(), e -> convertArrayToSet(e.getValue())));
    }
    

    我使用了ArraysCollectors 的静态导入来缩短 sn-ps。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-24
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-17
      相关资源
      最近更新 更多