I tried to generalize the map transfer method using Java 8 stream. Here is the code
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);
}
}
But I got this error message
Error:(66, 25) java: incompatible types: inference variable K has incompatible bounds
equality constraints: V
lower bounds: K
What do I need to change for it to work?
source
share