Java 8 将 HashSet 转换为 HashMap

Pan*_*hal 2 java lambda dictionary set java-8

我正在尝试使用 lambda 和 Collectors 转换hashsethashmapJava 8,但我失败了。下面是我的代码:

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));
Run Code Online (Sandbox Code Playgroud)

但上面给出的错误如下:

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)
Run Code Online (Sandbox Code Playgroud)

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

ass*_*ias 6

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

例如:

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