我试图使用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我要改变什么才能让它起作用?
发布于 2017-11-06 15:50:42
问题是,您实际上将值转换为键和副词到原始输入,但是由于您应用了保留与原始映射相同的键值类型的函数,所以在平面地图操作之后,您将得到一个Stream<Tuple2<V, K>>,所以集合再次返回一个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)https://stackoverflow.com/questions/47140241
复制相似问题