简体   繁体   中英

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. 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. Any help?

There are two issues: toMap() returns a Map, not necessarily a HashMap, and the second argument needs to be a function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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