Different ways to iterate over Collections in Java

Below examples uses different techniques to iterate over java collections. Use what’s suitable and easy for you in any situation.

  1. Iterable.forEach method (Java 8)

    Recently introduced in java 8, This method can be called on any Iterable and takes one argument implementing the functional interface java.util.function.Consumer. e.g.

    Collection<String> collection = Arrays.asList("How", "To", "Iterate", "In", "Java");
    
    collection.forEach(s -> System.out.println(s));
    

    The Array class does not yet implement Iterable, so you cannot use this technique directly on arrays.
  2. Java “foreach” loop (Java 5)

    The “foreach” loop syntax is:

    for (Type var : Iterable<Type>) {
            // do something with "var"
    }

    e.g.

    Collection<String> collection = Arrays.asList("How", "To", "Iterate", "In", "Java");
    		
    for(String s : collection) {
    	System.out.println(s);
    }
    
  3. java.util.Iterator (Java 2)

    Using Iterator is still very popular way to iterate over collections, mainly due to addtional methods it provide to manipulate the collection elements.

    Collection<String> collection = Arrays.asList("How", "To", "Iterate", "In", "Java");
    		
    Iterator<String> itr = collection.iterator();
    
    while(itr.hasNext()) {
    	System.out.println(itr.next());
    }
    
  4. Traditional for loop

    This is most appropriate when dealing with indexed collections such as list. It uses the standard for loop invented in the early 1970s in the C language. The loop syntax is:

    for (init; test; change) {
            // do something
    }

    e.g.

    List<String> list = Arrays.asList("How", "To", "Iterate", "In", "Java");
    		
    for( int i=0; i < list.size(); i++ )
    {
    	System.out.println(list.get(i));
    }
    

Happy Learning !!

References:

For each loop
Iterable

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial