Getting the stream object in Collectors toMap method using Method References in Java 8

Saurav Ojha :

I am trying to iterate a list using stream() and putting in a map, where the key is the steam element itself, and the value is an AtomicBoolean, true.

List<String> streamDetails = Arrays.asList("One","Two");
toReplay = streamDetails.stream().collect(Collectors.toMap(x -> x.toString(), new AtomicBoolean(true)));

I get the below errors at compile time.

Type mismatch: cannot convert from String to K
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) -> {}, 
     AtomicBoolean)

What could I be doing wrong, what shall I replace my x -> x.toString() with?

ernest_k :

new AtomicBoolean(true) is an expression that is not valid for the second parameter to Collectors.toMap.

toMap here would want a Function<? super String, ? extends AtomicBoolean> (intended to convert a stream element (or type String) to a map value of your intended type, AtomicBoolean), and a correct argument could be:

Collectors.toMap(x -> x.toString(), x -> new AtomicBoolean(true))

Which can also be written using Function.identity:

Collectors.toMap(Function.identity(), x -> new AtomicBoolean(true))

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=409924&siteId=1