Java - Collection, Iterator and Comparator
Java Collection Framework hierarchy
A collection is a container object that holds a group of objects, often referred to as data or elements.
The Java Collections Framework supports two types of collections:
- For storing a collection, simply called
collection
- For storing key/value pairs, called
map
map
is not in the collection
The Collection interface is for manipulating a collection of objects.
Iterators
Iterator is a classic design pattern for walking through a data structure without having to expose the details of how data is stored in the data structure.
Each collection is Iterable. You can obtain its Iterator object to traverse all the elements in the collection.
1 | import java.util.*; |
List Iterator
The ListIterator interface extends the Iterator interface to add bidirectional traversal of the list.
In the List interface there are 2 concrete implementations. ArrayList and LinkedList.
Showcasing the bidirectional traversal of the list.
1 | import java.util.*; |
Comparing Objects
Comparable Interface Abstract Classes and Interfaces
The Comparable Interface
1 | // This interface is defined in |
The classes Byte, Short, Integer, Long, Float, Double, Character, BigInteger, BigDecimal, Calendar, String, and Date all implement the Comparable interface.
Note the classes Number does not implement the Comparable interface.
Generic sort Method
The java.util.Arrays.sort(array)
method requires that the elements in an array are instances of Comparable<E>
.
Since all Comparable objects have the compareTo method, the java.util.Arrays.sort(Object[]) method in the Java API uses the compareTo method to compare and sorts the objects in an array.
Comparator Interface From Lists, Stacks, Queues, and Priority Queues
What If the objects are not instances of Comparable?
- You can define a comparator to compare these elements.
- The
Comparator
interface has thecompare
method for comparing two objects.
1 | public interface Comparator<T> { |
Lambda Expression in Comparator
Comparator is a functional interface. It has just a single method, compare. We can use lambda expression to simplify coding.
java.util.Arrays.sort(cities, (s1, s2) −> {return s1.length() − s2.length();});
Or simply
java.util.Arrays.sort(cities, (s1, s2) −> s1.length() − s2.length());
SortStringIgnoreCase
There is method that allows you to sort but ingoring case.
1 | public class SortStringIgnoreCase { |
1 | public class SortStringIgnoreCase { |
The reversed() method
- The default reversed() method can be used to reverse the order for a comparator.