Reputation: 16053
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?
Upvotes: 3
Views: 7304
Reputation: 432
final Map map = set.stream() .collect(Collectors.toMap(Function.identity(), key -> 0));
Upvotes: 1
Reputation: 328598
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));
Upvotes: 7