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

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “Different ways to iterate over Collections in Java”

  1. Here you explained different-different ways to iterate the elements from a collection.
    this article is useful.
    thanks for this great article.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.