通用toMap Collector无法编译

时间:2016-06-08 13:32:40

标签: java generics java-8 java-stream collectors

我正在尝试创建一个相当简单的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,我也遇到了问题。

1 个答案:

答案 0 :(得分:5)

这是因为您为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);
    }
}
祝你好运!