Iterator, Comparator, and Comparable
Explore how to implement and use the Iterator, Comparator, and Comparable interfaces in Java. Understand their roles in sorting and traversing collections, including how to handle common issues with comparison logic. Gain practical experience applying these interfaces to manage ordered data effectively in programming.
We'll cover the following...
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:
First of all, we sort the names of the account holders. Then, we print the names of account holders based on sorted account numbers in ascending order.
Printing the sorted names of account holders:
Amubrata, Hicky, John, Jason, Sanjib,
Printing names of account holders based on sorted account numbers in ascending order:
John : 201, Amubrata : 202, Sanjib : 203, Hicky : 204, Jason : 205,