【问题标题】:Java 8 Convert HashSet to HashMapJava 8 将 HashSet 转换为 HashMap
【发布时间】:2015-12-08 11:48:28
【问题描述】:

我正在尝试使用 lambda 和 Collectors 在 Java 8 中将 hashset 转换为 hashmap,但我没有这样做。下面是我的代码:

Set<String> set = new HashSet<String>();
set.add("1");
set.add("2");
set.add("3");
HashMap<String, Integer> map = set.stream().collect(Collectors.toMap(x -> x, 0));

但上面给出的错误如下:

The method toMap(Function<? super T,? extends K>, Function<? super T,? extends U>) in the type Collectors is not applicable for the arguments ((<no type> x) -> {}, int)

我是 lambdas 的新手。有什么帮助吗?

【问题讨论】:

    标签: java dictionary lambda set java-8


    【解决方案1】:

    有两个问题:toMap()返回一个Map,不一定是HashMap,第二个参数需要是一个函数。

    例如:

    Map<String, Integer> map = set.stream().collect(Collectors.toMap(x -> x, x -> 0));
    

    【讨论】:

      【解决方案2】:

      最终地图 map = set.stream() .collect(Collectors.toMap(Function.identity(), key -> 0));

      【讨论】:

        猜你喜欢
        • 2019-12-06
        • 2017-06-16
        • 2021-07-11
        • 1970-01-01
        • 1970-01-01
        • 2015-01-14
        • 1970-01-01
        • 2019-02-03
        • 1970-01-01
        相关资源
        最近更新 更多