Understanding complex generics syntax

Let's understand what the below generics syntax mean

public static <K extends Comparable<? super K>, V>  Comparator<Map.Entry<K,V>> comparingByKey() {
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> c1.getKey().compareTo(c2.getKey());
 }

Here, the method comparingByKey() returns Comparator of Map.Entry object; which is Comparator<Map.Entry<K,V>> where K and V are generic types of Key and Value. But, what values K and V accept?

And what is <K extends Comparable<? super K>, V> in the above syntax??
It describes/defines what types K, V, and Comparable accepts.

Let's split the above syntax into 2 parts.
1. K extends Comparable<? super K> - Key
2. V - Value

1. <K extends Comparable<? super K>  -  
For time being ignore <? super K>, then your above syntax looks like <K extends Comparable>. 

This syntax tells Generic type K is a subtype of Comparable (comparingByKey() compares keys of Entry object; So, the key of the Entry object has to be Comparable). So, defining the type of K is completed. Let's define what should be the type of Comparable.

What should be the type of Comparable??
public interface Comparable<T>  is the syntax of the Comparable class.

So, we must define what should be the allowed for T generic type of Comparable and we defined
Comparable<? super K> which says either **Comparable class is implemented by 'K' itself or any of K's superClass has implemented**.

2. V - There are no type bounds declared on V.

public static <K extends Comparable<? super K>, V>  Comparator<Map.Entry<K,V>> comparingByKey()

If we sum up what we have discussed, comparingByKey() returns Comparator<Map.Entry> instance of Key K and Value V types.
where K - is a Comparable (Subtype of Comparable)
and Comparable - is K or superClass of K

Comments

Popular posts from this blog

Distributed database design using CAP theorem

SQL Analytical Functions - Partition by (to split resultset into groups)

Easy approach to work with files in Java - Java NIO(New input output)