Wee*_*ooo 1 java java-8 java-stream
我想要List<InstanceWrapper>
为每个元素做一些逻辑运算,从而得出一些结论String message
。然后,我要进行create Map<String, String>
,其中key是InstanceWrapper:ID
,value是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));
}
Run Code Online (Sandbox Code Playgroud)
但是它不会编译,我会明白,如何将stream().map()
结果转化为collectors.toMap()
价值?
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>>)
Run Code Online (Sandbox Code Playgroud)
因为这时你得到你不能收集绘制地图之前,Stream
的String
S和松动有关的信息InstanceWrapper
。Stream#toMap
需要两个lambda,一个用于生成键,第二个用于生成值。应该是这样的:
instances.stream()
.collect(Collectors.toMap(InstanceWrapper::getID, instance -> handle(instance, status));
Run Code Online (Sandbox Code Playgroud)
第一个lambda生成键:InstanceWrapper::getID
,第二个lambda生成值:instance -> handle(instance, status)
。
归档时间: |
|
查看次数: |
65 次 |
最近记录: |