通用 toMap 收集器无法编译

Generic toMap Collector cannot compile

我正在尝试创建一个相当简单的 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<K, V>, ?, Map<K, V> 收集器收集 Entry<String, Object> 流。您正在寻找的可能是这样的:

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);
    }
}

祝你好运!