Cannot Infer Type Variables for Collectors.toMap

Viewed 1667

I'm trying to create an EnumMap that simply maps the enum's constants to their respective ordinals. I figured I could do so succinctly like so:

private static Map<Rank, Integer> defaultRankOrdering = new EnumMap<>(
    Arrays.stream(Rank.values()).collect(
        Collectors.toMap(Function::identity, e -> e.ordinal())));

However, the compiler says it cannot infer any of the type variables for toMap. I don't see why, considering that, per the two-argument signature of toMap:

public static <T, K ,U> Collector<T, ? ,Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,
                                                         Function<? super T, ? extends U> valueMapper)

T should be inferred to be Rank, as Arrays.stream(Rank.values()) is a Stream<Rank>, K should also be inferred to be Rank, as Function.identity returns a Function<T, T>, and U should be inferred to be Integer because the return type of Enum.ordinal is int, which should be boxed to Integer in this case.

Any help would be greatly appreciated.

2 Answers
Related