Java 8 type inference error

Viewed 106

I tried to generalize my map transposing 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);
    }

    // constructor and getters omitted
}

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 have to change for it to work?

1 Answers

The thing is that you actually transpose the values as keys and vice-versae to your original input, but since you apply functions that preserves the same key value types as in the original map, you end up with a Stream<Tuple2<V, K>> after your flatmap operation, so the collect returns a Map<K, Collection<V>> again.

So the method header should be:

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)
Related