简体   繁体   English

Java 8将HashSet转换为HashMap

[英]Java 8 Convert HashSet to HashMap

I'm trying to convert hashset to hashmap in Java 8 using lambda and Collectors but I'm failing to do so. 我正在尝试使用lambda和Collectors将hashset转换为hashset中的hashmap ,但我没有这样做。 Below is my code : 以下是我的代码:

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));

But the above is giving error as following: 但上面给出的错误如下:

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)

I'm a newbie in lambdas. 我是lambdas的新手。 Any help? 有帮助吗?

There are two issues: toMap() returns a Map, not necessarily a HashMap, and the second argument needs to be a function. 有两个问题: toMap()返回一个Map,不一定是HashMap,第二个参数需要是一个函数。

For example: 例如:

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

final map map = set.stream()。collect(Collectors.toMap(Function.identity(),key - > 0));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM