Table of Contents

  1. Review of Loop Contructs
  2. Concept of the Iterator
  3. Collections Looping Approaches

Review of Loop Constructs

In Java, there are 2 main loop constructs: for and while. Let us review each of these in turn.

for Loop

Since Java 5, there are 2 forms of for loop: classic and enhanced. The classic for loop is in the form:

for (initialization; termination; increment/decrement) {
  statement(s)
}
The enhanced for loop is in the form:

for (type : collection) {
  statement(s)
}
The major difference between the 2 for loops is that the classic for loop allows us to keep track of the index or position of the collection.

while Loop

There are again 2 forms of while loop: while and do-while. The while loop is in the form:

while (expression) {
  statement(s)
}
The do-while loop is in the form:

do {
  statement(s)
} while (expression);
The major difference between the 2 while loops is that the do-while will execute at least once.

Concept of the Iterator

An iterator is an object that enables us to traverse a collection. There is an iterator (java.util.Iterator) in all the top level interfaces of the Java Collections Framework that inherits java.util.Collection interface. These interfaces are java.util.List, java.util.Queue, java.util.Deque, and java.util.Set. Furthermore, there is the java.util.Map interface that does not inherit java.util.Collection.



Lists also have a special iterator called a list iterator (java.util.ListIterator). What’s the difference? The java.util.Iterator is forward looking only while the java.util.ListIterator is bidirectional (forward and backward). Furthermore, the java.util.ListIterator inherits java.util.Iterator. The result of using either iterator to loop through a list will be the same as we will see later.

 

Java Collections Looping Approaches

Can you guess how many ways we can loop through a collection given there are 2 forms of loop constructs and all interfaces have an iterator.

Iterate through List Collections

We declare a list of strings and populate it.

List<String> strList = new ArrayList<String>();
strList.add("list item 1");
strList.add("list item 2");
strList.add("list item 3");
strList.add("list item 4");
strList.add("list item 5");
The enhanced for loop is the first way and most direct.

for (String s : strList) {
  System.out.println(s);
}
Next is the classic for loop, which uses an iterator.

for (Iterator<String> it = strList.iterator(); it.hasNext(); ) {
  System.out.println(it.next());
}
Notice that there is no increment/decrement in this classic for loop.

We mentioned earlier that Lists have a special iterator called ListIterator. We can easily replace for loop’s initialization to either of the following and it would work as well.

ListIterator<String> it = strList.listIterator();
Iterator<String> it = strList.listIterator();
Next is the while loop, which is basically the classic for loop represented in a different format.

Iterator<String> itA = strList.iterator();
while (itA.hasNext()) {
  System.out.println(itA.next());
}
Similarly the iterator declaration (variable itA) can be replaced to either of the following and it would work as well.

ListIterator<String> itA = strList.listIterator();
Iterator<String> itA = strList.listIterator();
Finally the last approach is the do-while loop. We can easily refactor the while loop to become a do-while loop as shown below.

Iterator<String> itB = strList.iterator();
do {
  System.out.println(itB.next());
} while (itB.hasNext());
Again the iterator declaration (variable itB) can be replaced with the list iterator form.

ListIterator<String> itB = strList.listIterator();
Iterator<String> itB = strList.listIterator();
In addition to using the iterator, we can use the List’s position or index. The classic for loop:

for (int i=0; i<strList.size(); i++) {
  System.out.println(strList.get(i));
}
The variable i inside the above for loop indicates the current position or index of the list.

The while loop:

int i=0;
while (i<strList.size()) {
  System.out.println(strList.get(i));
  i++;
}
The do-while loop:

int j=0;
do {
  System.out.println(strList.get(j));
  j++;
} while (j<strList.size());

Iterate through Queue Collections

We declare a queue of strings and populate it.

Queue<String> strQueue = new PriorityQueue<String>();
strQueue.add("queue item 1");
strQueue.add("queue item 2");
strQueue.add("queue item 3");
strQueue.add("queue item 4");
strQueue.add("queue item 5");
The enhanced for loop:

for (String s : strQueue) {
  System.out.println(s);
}
The classic for loop:

for (Iterator<String> it = strQueue.iterator(); it.hasNext(); ) {
  System.out.println(it.next());
}
The while loop:

Iterator<String> itA = strQueue.iterator();
while (itA.hasNext()) {
  System.out.println(itA.next());
}
The do-while loop:

Iterator<String> itB = strQueue.iterator();
do {
  System.out.println(itB.next());
} while (itB.hasNext());

Iterate through Deque Collections

We declare a deque of strings and populate it.

Deque<String> strDeque = new ArrayDeque<String>();
strDeque.add("deque item 1");
strDeque.add("deque item 2");
strDeque.add("deque item 3");
strDeque.add("deque item 4");
strDeque.add("deque item 5");
Here we are using this deque as a queue. If we were to use it as a stack, then we would have used the push() method to populate the deque.

The enhanced for loop:

for (String s : strDeque) {
  System.out.println(s);
}
The classic for loop:

for (Iterator<String> it = strDeque.iterator(); it.hasNext(); ) {
  System.out.println(it.next());
}
The while loop:

Iterator<String> itA = strDeque.iterator();
while (itA.hasNext()) {
  System.out.println(itA.next());
}
The do-while loop:

Iterator<String> itB = strDeque.iterator();
do {
  System.out.println(itB.next());
} while (itB.hasNext());

Iterate through Set Collections

We declare a set of strings and populate it.

Set<String> strSet = new HashSet<String>();
strSet.add("set item 1");
strSet.add("set item 2");
strSet.add("set item 3");
strSet.add("set item 4");
strSet.add("set item 5");
The enhanced for loop:

for (String s : strSet) {
  System.out.println(s);
}
The classic for loop:

for (Iterator<String> it = strSet.iterator(); it.hasNext(); ) {
  System.out.println(it.next());
}
The while loop:

Iterator<String> itA = strSet.iterator();
while (itA.hasNext()) {
  System.out.println(itA.next());
}
The do-while loop:

Iterator<String> itB = strSet.iterator();
do {
  System.out.println(itB.next());
} while (itB.hasNext());

Iterate through Map collections

We declare a map of string keys with string values and populate it.

Map<String, String> strMap = new HashMap<String, String>();
strMap.put("key 1", "value 1");
strMap.put("key 2", "value 2");
strMap.put("key 3", "value 3");
strMap.put("key 4", "value 4");
strMap.put("key 5", "value 5");
The enhanced for loop:

for (Map.Entry<String, String> entry : strMap.entrySet()) {
  System.out.println(entry.getKey() + "=" + entry.getValue());
}
The classic for loop:

for (Iterator<String> it = strMap.keySet().iterator(); it.hasNext(); ) {
  String key = it.next();
  System.out.println(key + "=" + strMap.get(key));
}
The while loop:

Iterator<String> itA = strMap.keySet().iterator();
while (itA.hasNext()) {
  String key = itA.next();
  System.out.println(key + "=" + strMap.get(key));
}
The do-while loop:

Iterator<String> itB = strMap.keySet().iterator();
do {
  String key = itB.next();
  System.out.println(key + "=" + strMap.get(key));
} while (itB.hasNext());
To summarize, there are 4 major approaches to loop through a collection in general. Lists have 10 approaches because of a) the extra specialized iterator and b) able to retrieve elements directly given its position in the loop.

 

Related Tutorials:

 

Other Java Collections Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (java_collections_looping_summary.pdf)java_collections_looping_summary.pdf[Summary of the looping approaches of the Java Collections Framework]154 kB

Add comment