4

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 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I just figured it out that I don't have to swap the key/value twice because the mappers already did.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.