Sunday, June 28, 2015

Sorting Key-Value pairs in Java

Saw making your own sorting logic by implementing Comparable or Comparator? If not, click here. Now, how about sorting key-value pairs! Well, we need just a little code modification. See following code sample that sorts key-value pairs, first by key, then values. Look at the compareTo method implementation.

Sunday, June 7, 2015

Comparable and Comparator- When and how to use? [Concise]

When there comes the need of sorting objects, be it using Collections.sort() or just adding elements to Treeset etc, java.lang.Comparable and java.util.Comparator come into picture. For default sorting of objects in the collection, we need to implement Comparable and override below method in that class, unless we are using some pre-defined class that already implements Comparable like String, Integer etc.,
int compareTo(T o)
If we want to provide an external sorting logic to override the default one, the class needs to implement Comparator interface and override the following method:
int compare(T o1, T o2)
The question: Why use Comparator when we already have Comparable?
Answer: If you have authored that class, then you can give a default sorting behavior by implementing Comparable and use that logic to sort whenever needed. Now, let's say that you are using an existing class whose source you can not modify and the default sorting logic of which you are not satisfied with. What now? Just write a Comparator using your own sorting process and use that instance to sort. See below sample programs.

The API information is here:
1. java.lang.Comparable
2. Java.util.Comparator
Lets dig into this with our custom class.