Java 8将HashSet转换为HashMap

时间:2015-12-08 11:48:29

标签: java dictionary lambda set java-8

我尝试使用lambda和收集器在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的新手。有什么帮助吗?

2 个答案:

答案 0 :(得分:3)

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

例如:

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

答案 1 :(得分:0)

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