首页 > 解决方案 > Getting the stream object in Collectors toMap method using Method References in Java 8

问题描述

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?

标签: javacollectionsjava-8java-streammethod-reference

解决方案


new AtomicBoolean(true)是对 的第二个参数无效的表达式Collectors.toMap

toMap这里需要一个Function<? super String, ? extends AtomicBoolean>(旨在将流元素(或字符串类型)转换为您想要的类型的映射值,AtomicBoolean),并且正确的参数可能是:

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

也可以使用以下方式编写Function.identity

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

推荐阅读