字典Java 8将HashSet转换为HashMap
我正在尝试使用lambda和收集器将Java8中的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)
我是兰巴斯的新手。有什么帮助吗
# 1 楼答案
有两个问题:
toMap()
返回一个映射,不一定是HashMap,第二个参数需要是一个函数例如:
# 2 楼答案
最终贴图=设置。流() .collect(Collectors.toMap(Function.identity(),key->;0));