我试图使用 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
我必须更改什么才能使其正常工作?
问题是您实际上将值转置为键,反之亦然原始输入,但由于您应用的函数保留了与原始映射中相同的键值类型,因此在平面图操作后最终会出现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)