Java custom Comparators and examples

Java custom Comparators are important to sort the user defined classes. Here we give examples on how to implement user defined Comparators and use them. They are in String, PriorityQueue and TreeMap.

1. Java custom Comparators for String

When sorting strings, it is sorted by Alphabetical order by default. However you can override compare() to make strings sorted by custom design. For example, You can sort the string by their length. Here are the examples of defining Java string comparators.

2. PriorityQueue

The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time. The easy way is to define a separate custom Comparator class that implements Comaraptor interface and compare() method. Then you can create new PrirorityQueue object with the new custom Comparator you just created. Here are a few examples of Java PriorityQueue Comparator implementations and uses.

3. TreeMap (TreeSet)

HashMap in Java does not guarantee the order of the map. But TreeMap does. TreeMap implements SortedMap interface. It is sorted in the ascending order of its keys.If you want to sort by value, you have to implement comparator for that. The same applies to HashSet and TreeSet.

Java coding interview pocket book (2nd edition)
Java coding interview questions series (YouTube)

Comments are closed