繁体   English   中英

Java 8将HashSet转换为HashMap

[英]Java 8 Convert HashSet to HashMap

我正在尝试使用lambda和Collectors将hashset转换为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的新手。 有帮助吗?

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

例如:

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