Java Iterator examples

Here are few Java Iterator examples for your reference. Below are the three ways to iterate a List or Set in Java –

  • Using iterator.hasNext()
  • Using iterator.forEachRemaining() method
  • Using  ListIterator

 

1. Iterator Example with iterator.hasNext()

Get Iterator from a List and loop over it.

package com.codehelp.java8;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class JavaIteratorExample1 {
    public static void main(final String[] args) {
        final List list = Arrays.asList("Java", "Kotlin", "Python", "Scala", "Swift");
        final Iterator iterator = list.iterator();

        while (iterator.hasNext()) {

            final String language = iterator.next();
            System.out.println(language);

        }
    }
}

 

2. Iterator Example with iterator.forEachRemaining()

In Java 8, there is a new forEachRemaining() method added into the Iterator. It also provides a Consumer argument to let us defined how to consume the item of the list.

package com.codehelp.java8;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class JavaIteratorExample2 {
    public static void main(String[] args) {
        
        final List list = Arrays.asList("Java", "Kotlin", "Python", "Scala", "Swift");
        final Iterator iterator = list.iterator();

        iterator.forEachRemaining(System.out::println);

        
    }
}

 

3. Iterator Example with ListIterator

Java 8 ListIterator extends Iterator to provide extra features like

  • Traverse the list in either direction, next() and previous()
  • Modify the list during iteration, add() and set()
  • Get the iterator’s current position in the list, nextIndex() and previousIndex()
package com.codehelp.java8;

import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;

public class JavaIteratorExample3 {
    public static void main(final String[] args) {

        final List list = Arrays.asList("Java", "Kotlin", "Python", "Scala", "Swift");

        // get ListIterator, start from list's index 3
        final ListIterator iterator1 = list.listIterator(3);
        iterator1.forEachRemaining(System.out::println);

        // get ListIterator, start from list's index 0
        final ListIterator iterator2 = list.listIterator();
        iterator2.forEachRemaining(System.out::println);

    }
}

 

References:

 

 

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.