java - 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?
解决方案
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))
推荐阅读
- qml - 在密码文本字段上,我想应用一个不隐藏显示密码的选项,供用户在 qml 中检查和确认
- angular - 将 debounceTime 添加到 HttpInterceptor
- python-3.x - 检查 Python 中是否存在带有 pathlib 的文件并返回假阴性
- javascript - 使用 React 从功能组件中的类组件访问 ref
- python-3.x - 如何使用也具有外键字段的外键字段进行更新
- android - 有没有办法查看 PC 的 Android 端到 Android 的连接?
- c++ - c ++如何在自定义容器中正确调用deallocate
- java - java.lang.IllegalArgumentException:无法在 Corda 中接收原始类型 [int]
- r - 使用 renderUI 在 R Shiny 中插入额外的 tabPanel
- javascript - 当对象在另一个对象内时,如何通过其 id 找到对象