使用 Java 8 中的方法引用获取 Collectors toMap 方法中的流对象

Sau*_*jha 2 java collections java-8 java-stream method-reference

我正在尝试使用stream()并放入地图来迭代列表,其中键是 steam 元素本身,值是 AtomicBoolean,true。

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

我在编译时收到以下错误。

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)
Run Code Online (Sandbox Code Playgroud)

我可能做错了什么,我应该用什么x -> x.toString()来代替?

ern*_*t_k 6

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

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

Collectors.toMap(x -> x.toString(), x -> new AtomicBoolean(true))
Run Code Online (Sandbox Code Playgroud)

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

Collectors.toMap(Function.identity(), x -> new AtomicBoolean(true))
Run Code Online (Sandbox Code Playgroud)