java - Stream().map() 结果作为 Collectors.toMap() 值

标签 java dictionary generics java-8 java-stream

我有 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>>)

最佳答案

您不能在收集到映射之前进行映射,因为那样您将获得 StringStream 并丢失有关 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/

相关文章:

java - 检查 geoFence 内的 Geopoint 和 Java 中的距离

java - volatile 变量未读取其更新值

python - 从具有重复行名称的文件创建字典

c# - 将泛型传递到类构造函数列表中

java - 获取从非泛型类型类扩展的类的泛型类型

java - 对 TreeMap java 中的值进行排序

java - 是否有可能在java中获取变量堆上的地址?

python - 我们可以将两种类型的值分配给字典中的键吗

c# - 对包含字典的对象列表进行排序

c# - 自引用泛型参数