Tech Master Tutorials
Email Facebook Google LinkedIn Pinterest Twitter
Home Java Java 8 Java Interview Questions Java Programming

Traversing Through a Collection

We can traverse through a collection using the following three ways -

  • for-each construct
  • Iterators
  • Aggregate Operations
for-each Construct

For-each allows to traverse an array or collection using a loop. Using for-each we can go through each element and perform some operation like printing the value for the element as shown in the below code snippet. In the below code, a collection to hold string has been prepared which uses an array list and using for-each construct traversing and printing the array list values.

public class TraversalTest {
	
	public static void main(String[] args) {
		Collection<String> strCollection=new ArrayList<String>();
		strCollection.add("India");
		strCollection.add("US");
		strCollection.add("UK");
		
		for (String string : strCollection) {
			System.out.println(string);
		}	
	}
		
}

Iterators

An Iterator object enables us to traverse through a collection. Using iterator we can also remove the elements from the collection. Using iterator() method from collection we can get the iterator for the collection and we can traverse through the collection.

public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove(); //optional
}

Iterator interface has got the following methods:

  1. boolean hasNext() – returns true if iterator has more elements to be traversed
  2. next() – returns the next element in the iteration
  3. remove() – removes the last element from the collection that was returned by the next. It can be called only once after the next() has been called otherwise throws exception. Interator is the only safe way to modify a collection during iteration. In any other case unexpected events can happen.

Following is the code snippet to traverse Collection using iterator.

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class TraversalTestIterator {
	public static void main(String[] args) {
		Collection<String> strCollection=new ArrayList<String>();
		strCollection.add("India");
		strCollection.add("US");
		strCollection.add("UK");
		Iterator<String> itr=strCollection.iterator();
		while (itr.hasNext()) {
			String string = (String) itr.next();
			System.out.println(string);
		}	
	}	
}

Aggregate Operations

JDK 8 release has introduced a new method which is also preferred method to traverse that is to obtain a stream over the collection and perform aggregate operations on it. Some of the aggregate operations are provided with the capability to use lambda expressions with them. Lambda expressions provides the capability to pass the code as parameters in the form of functional interfaces. Lambda expressions make the code short(lesser lines of code) and expressive.
The following code iterates through the Collection and prints the values:

import java.util.ArrayList;
import java.util.Collection;
import java.util.stream.Collectors;

public class TraversalUsingAggregateFun {
	public static void main(String[] args) {
		Collection<String> strCollection=new ArrayList<String>();
		strCollection.add("India");
		strCollection.add("US");
		strCollection.add("UK");
		
			
		//In the below code, first we are getting the stream on the collection and  
		//traversing using the forEach() function. 
		//In the below example, in the forEach method, we are passing a lambda expression. 
		//Lambda expression provide the capability to write the code with lesser number 
		//of line and make the code more expressive.
			
			strCollection.stream()
			.forEach(s -> System.out.println(s));
			
		
		//Stream API also provides a parallel stream which will work efficiently with 
		//a large collection if computer system got multiple cores.
		//In the below code example, we can also get the parallel stream and 
		//perform the traversing over the collection. Just we have use the below 
		//lines of code :
            strCollection.parallelStream()
			.forEach(e -> System.out.println(e));


		//There are other methods provided as part of the stream API using which we 
		//can collect data and perform operations. For example, having a collection 
		//of string and want to join them using comma as shown in the below code 	
				
		    String joined = strCollection.stream()
		    .collect(Collectors.joining(", "));
		    System.out.println("Joined String --> "+joined);	
		
	}	
}