Java 8类型推断错误

ntviet18:

我试图使用Java 8流来概括我的地图转置方法。这是代码

public static <K, V> Map<V, Collection<K>> trans(Map<K, Collection<V>> map,
                                                     Function<? super K, ? extends V> f,
                                                     Function<? super V, ? extends K> g) {
        return map.entrySet()
                .stream()
                .flatMap(e -> e.getValue()
                        .stream()
                        .map(l -> {
                            V iK = f.apply(e.getKey());
                            K iV = g.apply(l);
                            return Tuple2.of(iK, iV);
                        }))
                .collect(groupingBy(Tuple2::getT2, mapping(Tuple2::getT1, toCollection(LinkedList::new))));
    }

public class Tuple2<T1, T2> {

    private final T1 t1;
    private final T2 t2;

    public static <T1, T2> Tuple2<T1, T2> of(T1 t1, T2 t2) {
        return new Tuple2<>(t1, t2);
    }

    // constructor and getters omitted
}

但是我得到了这个错误信息

Error:(66, 25) java: incompatible types: inference variable K has incompatible bounds
    equality constraints: V
    lower bounds: K

要使其正常工作,我需要更改什么?

亚历克西斯(Alexis C.):

问题是您实际上将值作为键转置,反之亦然转置到原始输入,但是由于您应用了保留与原始映射相同的键值类型的函数Stream<Tuple2<V, K>>,因此在进行flatmap操作后最终得到了a 收集Map<K, Collection<V>>再次返回

因此,方法标头应为:

public static <K, V> Map<K, Collection<V>> trans(Map<K, Collection<V>> map,
                                                 Function<? super K, ? extends V> f,
                                                 Function<? super V, ? extends K> g)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章