Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 230
Pankaj Singhal Avatar asked May 04 '26 08:05

Pankaj Singhal


2 Answers

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));
like image 131
assylias Avatar answered May 05 '26 20:05

assylias


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

like image 30
tzatalin Avatar answered May 05 '26 22:05

tzatalin