gpt4 book ai didi

java - 通用 toMap 收集器无法编译

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:07:09 26 4
gpt4 key购买 nike

我正在尝试创建一个相当简单的 Collector转换 Stream<Map.Entry>进入 Map ,但是 javac 提示泛型。无法弄清楚为什么它不起作用。

import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectorSO {
public static <K, V> void main(String[] args) {
Collector<Entry<K, V>, ?, Map<K, V>> collector = Collectors.toMap(Entry::getKey, Entry::getValue);
Stream<Entry<String, Object>> stream = Stream.empty();
Map<String, Object> map = stream.collect(collector);
}
}

编译器输出:

Error:(11, 41) java: no suitable method found for collect(java.util.stream.Collector<java.util.Map.Entry<K,V>,capture#1 of ?,java.util.Map<K,V>>)
method java.util.stream.Stream.<R>collect(java.util.function.Supplier<R>,java.util.function.BiConsumer<R,? super java.util.Map.Entry<java.lang.String,java.lang.Object>>,java.util.function.BiConsumer<R,R>) is not applicable
(cannot infer type-variable(s) R
(actual and formal argument lists differ in length))
method java.util.stream.Stream.<R,A>collect(java.util.stream.Collector<? super java.util.Map.Entry<java.lang.String,java.lang.Object>,A,R>) is not applicable
(cannot infer type-variable(s) R,A
(argument mismatch; java.util.stream.Collector<java.util.Map.Entry<K,V>,capture#1 of ?,java.util.Map<K,V>> cannot be converted to java.util.stream.Collector<? super java.util.Map.Entry<java.lang.String,java.lang.Object>,A,R>))

This表面上看起来很相似,但即使使用 JDK 1.8.0_60 我也遇到了问题。

最佳答案

这是因为您为 main 方法声明的类型变量。它们未在该上下文中捕获,因此您无法收集您的 Entry<String, Object>用你的 Entry<K, V>, ?, Map<K, V> 直播集电极。您正在寻找的可能是这样的:

public class CollectorSO
{
public static void main(String[] args)
{
Stream<Entry<String, Object>> stream = Stream.empty();
Map<String, Object> map = stream.collect(entryToMapCollector());
}

private static <K, V> Collector<Entry<K, V>, ?, Map<K, V>> entryToMapCollector()
{
return Collectors.toMap(Entry::getKey, Entry::getValue);
}
}

祝你好运!

关于java - 通用 toMap 收集器无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37704008/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com