Java 8 将 HashSet 转换为 HashMap

标签 java dictionary lambda set java-8

我正在尝试使用 lambda 和收集器将 hashset 转换为 Java 8 中的 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)

我是 lambda 的新手。有帮助吗?

最佳答案

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

例如:

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

关于Java 8 将 HashSet 转换为 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34155118/

相关文章:

java - 我怎样才能让 JScrollPane 填充 JPanel 的高度

dictionary - 在字典中将 c++/cli 类指定为 TValue 类型的正确语法是什么

python - 我怎样才能以一种有意义的方式阅读字典键?

c++ - 通过引用递归 lambda

c# - 无法将 Lambda 表达式转换为类型 'System.Type',因为它不是委托(delegate)类型

java - Gson如何获取序列化名称

java - Android不同对象的反序列化

java - 在同一类中的方法之外的任何地方访问整数

python - 使用 basemap 在 map 上放置饼图

c++ - Lamba 类型不是由模板函数或 auto 关键字推导出来的