我有 List<InstanceWrapper>
,对于每个元素,我想做一些逻辑,这将导致一些 String message
.然后,我想创建 Map<String, String>
,其中关键是 InstanceWrapper:ID
值为 message
;
private String handle(InstanceWrapper instance, String status) {
return "logic result...";
}
private Map<String, String> handleInstances(List<InstanceWrapper> instances, String status) {
return instances.stream().map(instance -> handle(instance, status))
.collect(Collectors.toMap(InstanceWrapper::getID, msg -> msg));
}
但它无法编译,我明白了,我该如何输入 stream().map()
结果变成collectors.toMap()
值(value)?
The method collect(Collector<? super String,A,R>) in the type Stream<String> is not applicable for the arguments (Collector<InstanceWrapper,capture#5-of ?,Map<String,Object>>)
最佳答案
您不能在收集到映射之前进行映射,因为那样您将获得 String
的 Stream
并丢失有关 InstanceWrapper
的信息。 Stream#toMap
采用两个 lambda - 一个生成键,第二个生成值。应该是这样的:
instances.stream()
.collect(Collectors.toMap(InstanceWrapper::getID, instance -> handle(instance, status));
第一个 lambda 生成键:InstanceWrapper::getID
,第二个 - 关联值:instance -> handle(instance, status)
。
关于java - Stream().map() 结果作为 Collectors.toMap() 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57721597/