Search code examples
javacollectionsguava

How Guava's Multimaps class's index() function works internally?


I am trying to understand Multimaps class's index function. If I want to use it like a HashMap then I can just put multiple values against a key and retrieve them with the same key.

But if I want to group the data according to some criteria then Multimaps implementation like this is used.

Now I have a doubt in below declaration of index function.

public static <K,V> ImmutableListMultimap<K,V> index(Iterator<V> values, Function<? super V,K> keyFunction)

If ImmutableListMultimap is to be returned with <K,V> then why does Function have the type declaration of <? super V,K>, which is exactly opposite?

Also how does the anonymous inner class of type Function works as shown in this example? I am not able to understand who calls the apply method defined inside the anonymous inner class Function?


Solution

  • If ImmutableListMultimap is to be returned with <K,V> then why does Function have the type declaration of <? super V,K>, which is exactly opposite?

    A Multimap has the two type parameters K for the keys and V for the values. The index method has the parameters Iterator<V> values (obviously for the values) and Function<? super V,K> keyFunction (for generating a key for a value).

    That means that the keyFunction has to accept a value (of type V or one of its supertypes, since you can pass any value of type V to a method accepting a supertype of V) and it has to return the key (of type K) for that value. This leads to the type Function<? super V,K>.

    Also how does the anonymous inner class of type Function works as shown in this example? I am not able to understand who calls the apply method defined inside the anonymous inner class Function?

    If you look at the implementation of the index method (https://github.com/google/guava/blob/v23.0/guava/src/com/google/common/collect/Multimaps.java#L1630), you will see that line 1637 that the index method calls keyFunction.apply(value)