Pankaj Singhal
Pankaj Singhal

Reputation: 16053

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?

Upvotes: 3

Views: 7304

Answers (2)

tzatalin
tzatalin

Reputation: 432

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

Upvotes: 1

assylias
assylias

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

Related Questions