Iterator, Comparator, and Comparable

Learn the difference between a comparator, a comparable, and an iterator.

The Java Collections Framework provides three important primary interfaces: Comparator, Comparable, and Iterator. Comparison plays a significant role in sorting and shuffling algorithms. Iteration is also crucial.

We’ll see a few code snippets where these three interfaces are implemented.

To sort elements, we can use TreeSet and TreeMap from the Java Collections Framework. But it’s the Comparator or the Comparable interface that precisely defines what sorted order means.

Java code for the Comparator interface

We can have objects that encapsulate ordering by implementing the Comparator and Comparable interfaces. Take a look at the following code snippet:

Get hands-on with 1200+ tech skills courses.