Collection Itteration

By | October 25th 2019 08:53:41 PM | viewed 186 times

The 4 Methods for Iterating Collections in Java

Iteration is one of the basic operations carried on a collection. Basically, an iteration takes elements from a collection one after another, from the first element to the last one.

For example, you may want to go through all students in a class to print their names or to find who have high scores in the recent exam. Or you may want to traverse through a list of numbers in order to calculate the sum and average. Such kinds of operations are very common in programming.

The Java programming language provides four methods for iterating over collections, including for loops, iterator and forEach (since Java 8).

Before going to each kind of iteration, suppose that we have a List collection as follows:

List listNames = new ArrayList<>();

listNames.add("Tom");
listNames.add("Mary");
listNames.add("Peter");
listNames.add("John");
listNames.add("Kim");
1. The Classic For Loop:

This iteration method is very familiar in programming in which a counter variable runs from the first element to the last one in the collection. Here’s the code that iterates over the listNames collection above:

for (int i = 0; i < listNames.size(); i++) {
	String aName = listNames.get(i);
	System.out.println(aName);
}
Output
Tom
Mary
Peter
John
Kim
2. The Iterator Method

Due to the limitations of the classic for loop, the Iterator method is created to allow us to iterate all kinds of collections. Thus you can see the Collection interface defines that every collection must implement the iterator() method.


Set numbers = new HashSet<>();

numbers.add(100);
numbers.add(35);
numbers.add(89);
numbers.add(71);

Iterator iterator = listNames.iterator();

while (iterator.hasNext()) {
	String aName = iterator.next();
	System.out.println(aName);
}
Output
35
100
71
89
And here's another example demonstrating how to iterate over a Map using an interator:
Map mapAscii = new HashMap<>();

mapAscii.put(65, "A");
mapAscii.put(66, "B");
mapAscii.put(67, "C");
mapAscii.put(68, "D");

Iterator keyIterator = mapAscii.keySet().iterator();

while (keyIterator.hasNext()) {
	Integer key = keyIterator.next();
	String value = mapAscii.get(key);
	System.out.println(key + " -> " + value);
}
Output
65 -> A
66 -> B
67 -> C
68 -> D
3. The Enhanced For Loop:

Since Java 5, programmers can use a more succinct syntax to iterate over a collection - It’s the enhanced for loop. For example, the following code uses the enhanced for loop to iterate over the listNames collection above:

Map mapAscii = new HashMap<>();

for (String aName : listNames) {
	System.out.println(aName);
}

And the code that iterates over a Map can be re-written using the enhanced for loop like this:

for (Integer key : mapAscii.keySet()) {
	String value = mapAscii.get(key);
	System.out.println(key + " -> " + value);
}
4. The forEach Method with Lambda Expressions:

Java 8 with Lambda expressions, introduces a totally new way for iterating over collections - it’s the forEach method. What’s the biggest difference between the forEach method and the previous ones?

listNames.forEach(name -> System.out.println(name));

To help you understand more. Suppose that we have some code to deal with each student name like this:

listNames.forEach(StudentHelper::process);

numbers.forEach(number -> System.out.println(number));

numbers.forEach(System.out::println);

mapAscii.forEach((key, value) -> System.out.println(key + " -> " + value));

bONEandALL
Visitor

Total : 19446

Today :43

Today Visit Country :

  • United States
  • The Netherlands
  • Singapore
  • Russia
  • China
  • India
  • Japan
  • Bulgaria
  • Lithuania