Iterator vs ListIterator

In this tutorial we will learn about the difference between Iterator and ListIterator . We will also look at the examples of Iterator and ListIterator one by one. We have already discussed different type of iterators  i.e fail-fast iterator and fail-safe iterator.

Difference between Iterator and ListIterator in Java with Example
 
1. Traversal Direction  :  ListIterator allows the programmers to iterate the list objects in both directions i.e forward as well as backward direction using previous() and next() method.
Iterator can be used to  iterate the list,map and set object in one direction i.e forward.

2.  Set and Map implemented Objects Traversal : ListIterator can be used to traverse List object only . But Iterator can be used to traverse Map, List and Set implemented objects.

for example
// ListIterator object is created
ListIterator listIteratorObject = List.listIterator();
// Iterator object is created
Iterator  iteratorObject  = List.iterator();

3. Add or Set operation at any index : According to ListIterator Oracle docs,
ListIterator can modify the list  during iteration using add(E e) , remove() or set(E e).
Iterator can not add the element during traversal but they can remove the element from the underlying collection during the iteration as they only consist of remove() method. There is no add(E e) and set(E e) method in Iterator.

4. Determine Iterator’s current position :  ListIterator can obtain the iterator’s current position in the list. Iterator’s current position during traversal can not be determined using Iterator.

5. Retrieve Index of the element : ListIterator can obtain the index of the elements using previousIndex(E e) or nextIndex(E e) methods. We can not obtain the index using Iterator as there is no such methods present.

Example of Iterator and ListIterator 

import java.util.Iterator;
import java.util.ListIterator;

public class IteratorListIteratorExample {
public static void main(String[] args) {

List listObject = new ArrayList();
listObject.add(“Alive is awesome”);
listObject.add(“Love yourself”);

ListIterator listIteratorObject = listObject.listIterator();
System.out.println(“ListIterator object output in forward direction:”);
System.out.println(“”);
while( listIteratorObject.hasNext() )
{
System.out.println(listIteratorObject.next());
}

System.out.println(“ListIterator object output in backward direction:”);
System.out.println(“”);
while( listIteratorObject.hasPrevious() )
{
System.out.println(listIteratorObject.previous());
}

List iteratorListObject = new ArrayList();

iteratorListObject.add(“Facebook”);
iteratorListObject.add(“Google”);
iteratorListObject.add(“Apple”);

Iterator javaHungryIterator = iteratorListObject.iterator();
System.out.println(“Iterator object output in forward direction:”);

while( javaHungryIterator.hasNext() )
{
System.out.println(javaHungryIterator.next());
}

}
}

Output :

ListIterator object output in forward direction:
Alive is awesome
Love yourself
ListIterator object output in backward direction:
Love yourself
Alive is awesome
Iterator object output in forward direction:
Facebook
Google
Apple

Similarities between Iterator and ListIterator in Java

1. Interfaces : Both Iterator and ListIterator are interfaces . ListIterator extends Iterator interface.

2. Collection Framework : Both Iterator and ListIterator are member of the Java Collection Framework.

3. Traversal : Both are used to iterate over the collection of objects .

4. Interfaces added to jdk : Both interfaces are added to the jdk in java 1.2

Recap : Difference between Iterator and ListIterator in Java with Example 

ListIterator Iterator
Traversal Direction Both , forward and backward Forward
Objects traversal List only Map, Set and List
Add and Set operations Allows both operations Not possible
Iterator’s current position Yes , can be determined Not possible.
Retrieve Index Yes Not possible

Java SortedMap and TreeMap

This tutorial helps you understand SortedMap with TreeMap implementation in the Java Collections Framework.First, let’s review the API hierarchy. TreeMap doesn’t only implement the Map interface, it also implements the SortedMapand NavigableMap interfaces. Therefore, besides the behaviors inherited from the Map, TreeMap also inherits the behaviors defined by SortedMap and NavigableMap. The following picture depicts the API hierarchy of TreeMap:

TreeMapAPI

1. Understanding SortedMap

The main characteristic of a SortedMap is that, it orders the keys by their natural ordering, or by a specified comparator. So consider using a TreeMap when you want a map that satisfies the following criteria:

  • null key or null value are not permitted.
  • The keys are sorted either by natural ordering or by a specified comparator.

The following example realizes the concept of a SortedMap:

1
2
3
4
5
6
7
8
9
SortedMap<String, String> mapDomains = new TreeMap<>();
mapDomains.put(".com", "International");
mapDomains.put(".us", "United States");
mapDomains.put(".uk", "United Kingdom");
mapDomains.put(".jp", "Japan");
mapDomains.put(".au", "Australia");
System.out.println(mapDomains);

Output:

1
{.au=Australia, .com=International, .jp=Japan, .uk=United Kingdom, .us=United States}

Here, this map contains mappings of domain=country, and as we see in the output, the domains (keys) are sorted by alphabetic order (natural ordering of Strings).

Besides the operations inherited from the Map interface, the SortedMap also defines the following operations:

  • Range view: returns a sub sorted map whose keys fall within a range of keys in the original map.
  • Endpoints: returns the first or last key in the sorted map.
  • Comparator access: returns the comparator (implements the Comparator interface), if any, used to sort the map.

Hence the following code is the definition of a SortedMap:

1
2
3
4
5
6
7
8
public interface SortedMap<K, V> extends Map<K, V>{
    Comparator<? super K> comparator();
    SortedMap<K, V> subMap(K fromKey, K toKey);
    SortedMap<K, V> headMap(K toKey);
    SortedMap<K, V> tailMap(K fromKey);
    K firstKey();
    K lastKey();
}

Let’s look at each type of operation in details. * Range View Operations:+ subMap(K fromKey, K toKey): returns a sorted map whose keys range from fromKey, inclusive, to toKey, exclusive.+ headMap(K toKey): returns a sorted map whose keys are strictly less than toKey.+ tailMap(K fromKey): returns a sorted map whose keys are greater than or equal to fromKey. * Endpoint operations:+ firstKey(): returns the first (lowest) key currently in the map.+ lastKey(): returns the last (highest) key currently in the map. * Comparator access:+ comparator(): returns the comparator used to order the keys in the map, or returns null if this map uses the natural ordering of its keys.

2. SortedMap and TreeMap Examples

The following code example demonstrates how to work with these operations on a TreeMap:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
SortedMap<Integer, String> mapHttpStatus = new TreeMap<>();
mapHttpStatus.put(100, "Continue");
mapHttpStatus.put(200, "OK");
mapHttpStatus.put(300, "Multiple Choices");
mapHttpStatus.put(400, "Bad Request");
mapHttpStatus.put(401, "Unauthorized");
mapHttpStatus.put(402, "Payment Required");
mapHttpStatus.put(403, "Forbidden");
mapHttpStatus.put(404, "Not Found");
mapHttpStatus.put(500, "Internal Server Error");
mapHttpStatus.put(501, "Not Implemented");
mapHttpStatus.put(502, "Bad Gateway");
System.out.println("All key-value pairs: ");
for (Integer code : mapHttpStatus.keySet()) {
    System.out.println(code + " -> " + mapHttpStatus.get(code));
}
System.out.println();
Integer firstKey = mapHttpStatus.firstKey();
String firstValue = mapHttpStatus.get(firstKey);
System.out.println("First status: " + firstKey + " -> " + firstValue);
System.out.println();
Integer lastKey = mapHttpStatus.lastKey();
String lastValue = mapHttpStatus.get(lastKey);
System.out.println("Last status: " + lastKey + " -> " + lastValue);
System.out.println();
SortedMap<Integer, String> map4xxStatus = mapHttpStatus.subMap(400, 500);
System.out.println("4xx Statuses: ");
for (Integer code : map4xxStatus.keySet()) {
    System.out.println(code + " -> " + map4xxStatus.get(code));
}
System.out.println();
SortedMap<Integer, String> mapUnder300Status = mapHttpStatus.headMap(300);
System.out.println("Statuses < 300: ");
for (Integer code : mapUnder300Status.keySet()) {
    System.out.println(code + " -> " + mapUnder300Status.get(code));
}
System.out.println();
SortedMap<Integer, String> mapAbove500Status = mapHttpStatus.tailMap(500);
System.out.println("Statuses > 500: ");
for (Integer code : mapAbove500Status.keySet()) {
    System.out.println(code + " -> " + mapAbove500Status.get(code));
}
Comparator comparator = mapHttpStatus.comparator();
System.out.println("Sorted by natural ordering? " + (comparator == null));

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
All key-value pairs:
100 -> Continue
200 -> OK
300 -> Multiple Choices
400 -> Bad Request
401 -> Unauthorized
402 -> Payment Required
403 -> Forbidden
404 -> Not Found
500 -> Internal Server Error
501 -> Not Implemented
502 -> Bad Gateway
First status: 100 -> Continue
Last status: 502 -> Bad Gateway
4xx Statuses:
400 -> Bad Request
401 -> Unauthorized
402 -> Payment Required
403 -> Forbidden
404 -> Not Found
Statuses < 300:
100 -> Continue
200 -> OK
Statuses > 500:
500 -> Internal Server Error
501 -> Not Implemented
502 -> Bad Gateway
Sorted by natural ordering? true   

And the following example shows how to use a comparator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
SortedMap<Integer, String> mapHttpStatus = new TreeMap<>(new ReverseComparator());
mapHttpStatus.put(100, "Continue");
mapHttpStatus.put(200, "OK");
mapHttpStatus.put(300, "Multiple Choices");
mapHttpStatus.put(400, "Bad Request");
mapHttpStatus.put(401, "Unauthorized");
mapHttpStatus.put(402, "Payment Required");
mapHttpStatus.put(403, "Forbidden");
mapHttpStatus.put(404, "Not Found");
mapHttpStatus.put(500, "Internal Server Error");
mapHttpStatus.put(501, "Not Implemented");
mapHttpStatus.put(502, "Bad Gateway");
for (Integer code : mapHttpStatus.keySet()) {
    System.out.println(code + " -> " + mapHttpStatus.get(code));
}

Here’s the code of the comparator class:

1
2
3
4
5
class ReverseComparator implements Comparator<Integer> {
    public int compare(Integer num1, Integer num2) {
        return num2.compareTo(num1);
    }
}

Output:

1
2
3
4
5
6
7
8
9
10
11
502 -> Bad Gateway
501 -> Not Implemented
500 -> Internal Server Error
404 -> Not Found
403 -> Forbidden
402 -> Payment Required
401 -> Unauthorized
400 -> Bad Request
300 -> Multiple Choices
200 -> OK
100 -> Continue

As you can see, this comparator sorts the map by the descending order of its keys.In case you are working on Java 8, use Lambda expressions to shorten the comparator code like this:

1
SortedMap<Integer, String> mapHttpStatus = new TreeMap<>((i1, i2) -> i2.compareTo(i1));

Class diagram of Queue API

Queue API is the most complex API in the family of Java Collections Framework. Queue<E> is the base interface for all kind of queues.

  • Sub interfaces: BlockingQueue<E>, Deque<E> and BlockingDeque<E>.
  • Abstract classes: AbstractQueue<E>.
  • Implementation classes:
    • ArrayBlockingQueue<E>
    • ArrayDeque<E>
    • ConcurrentLinkedQueue<E>
    • DelayQueue<E extends Delayed>
    • LinkedBlockingDeque<E>
    • LinkedBlockingQueue<E>
    • LinkedList<E>
    • PriorityBlockingQueue<E>
    • PriorityQueue<E>
    • SynchronousQueue<E>

The following class diagram outlines the hierarchy of Queue API:

Queue API class diagram

Class diagram of Map API

A map stores elements in terms of key=value pair. Map<K, V> is the base interface for all kind of maps.

  • Sub interfaces: ConcurrentMap<K, V>, SortedMap<K, V>, NavigableMap<K, V> and ConcurrentNavigableMap<K, V>.
  • Abstract classes: AbstractMap<E>.
  • Implementation classes:
    • Hashtable<K, V>
    • HashMap<K, V>
    • LinkedHashMap<K, V>
    • IdentityHashMap<K, V>
    • ConcurrentHashMap<K, V>
    • ConcurrentSkipListMap<K, V>
    • EnumMap<K extends Enum<K>, V>
    • WeakHashMap<K, V>
    • TreeMap<K, V>

The following class diagram outlines the hierarchy of Map API:

Map API class diagram

Class diagram of Set API

In Set API:

  • Set<E> is the base interface for all kinds of set. This interface extends all methods from the Collection<E>interface and does not define any new methods.
  • Sub interfaces: SortedSet<E> and NavigableSet<E>.
  • Abstract subclasses: AbstractSet<E> and EnumSet<E extends enum<E>>.
  • Concrete implementation classes: HashSet<E>, LinkedHashSet<E>, TreeSet<E>,ConcurrentSkipListSet<E> and CopyOnWriteArraySet<E> (these two last classes are under java.util.concurrent package).
  • The JobStateReasons class extends HashSet<E> but it is not a member of Java Collections Framework.

The following class diagram outlines the Set API in Java Collections Framework:

Set API class diagram

Class diagram of List API

In List API:

  • List<E> is the base interface for all kinds of list. It defines general operations for a List type.
  • Abstract subclasses: AbstractList<E> and AbstractSequentialList<E>
  • Concrete implementation classes: ArrayList<E>, Vector<E>, LinkedList<E> and CopyOnWriteArrayList<E>(this class is under java.util.concurrent package).
  • Legacy collection: Vector<E>
  • Implementation classes in JDK which are not members of Java Collections Framework: AttributeList,RoleList, RoleUnresolvedList and Stack.

The following class diagram describes the hierarchy structure of List API in Java Collections Framework:

List API class diagram

Overview of Java Collections Framework API (UML diagram)

The Java collections framework has a very complex API hierarchy.

The following class diagram shows a brief overview of the Java Collections Framework which is divided into four groups: List, Set, Map and Queue. Only the principal, commonly-used interfaces and classes are listed.

collections framework overview

 Class diagram of Java Collections framework

There are also more detailed class diagrams for each group: