Java Iterator examples

A few of Java Iterator and ListIterator examples.

1. Iterator

1.1 Get Iterator from a List or Set, and loop over it.

JavaIteratorExample1a.java

package com.mkyong;

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

public class JavaIteratorExample1a {

    public static void main(String[] args) {

        /*
        Set<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(3);
        set.add(4);
        set.add(5);

        Iterator<Integer> iterator = set.iterator();
        */

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        Iterator<Integer> iterator = list.iterator();

        while (iterator.hasNext()) {

            Integer result = iterator.next();
            System.out.println(result);

        }
    }

}

Output


1
2
3
4
5

1.2 Java 8, there is a new forEachRemaining added into the Iterator, it provides a Consumer argument to let us defined how to consume the item.

Iterator.java

    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }

Now, we can use lambdas to provide the implementation for the Consumer functional interface.

JavaIteratorExample1b.java

package com.mkyong;

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

public class JavaIteratorExample1b {

    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        Iterator<Integer> iterator = list.iterator();

        // lambda
        // iterator.forEachRemaining(x -> System.out.println(x));

        // Java 8, method reference
        iterator.forEachRemaining(System.out::println);

    }

}

Output


1
2
3
4
5

1.3 One more example for forEachRemaining.


        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        Iterator<Integer> iterator = list.iterator();

        iterator.forEachRemaining(x -> {
            System.out.println(x * 2);
        });

Output


2
4
6
8
10

1.4 Remove elements with Iterator.remove().

JavaIteratorExample1c.java

package com.mkyong;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class JavaIteratorExample1c {

    public static void main(String[] args) {

        // immutable list
        // List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

        // mutable list
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            Integer next = iterator.next();
            if (next == 3 || next == 4) {
                iterator.remove();
            }
        }

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

    }

}

Output


1
2
5

2. ListIterator

This 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()

2.1 Convert List to ListIterator.

JavaIteratorExample2a.java

package com.mkyong;

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

public class JavaIteratorExample2a {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("a", "b", "c", "d", "e");

        // get ListIterator, start from list's index 2
        ListIterator<String> iterator = list.listIterator(2);
        iterator.forEachRemaining(System.out::print);   // cde

        System.out.println("");

        // get ListIterator, start from list's index 0
        ListIterator<String> iterator2 = list.listIterator();
        iterator2.forEachRemaining(System.out::print);  // abcde
    }

}

Output


cde
abcde

2.2 Traverse the list in either direction, forward and backward.

JavaIteratorExample2b.java

package com.mkyong;

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

public class JavaIteratorExample2b {

    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

        ListIterator<Integer> iterator = list.listIterator();

        // loop to the end
        while (iterator.hasNext()) {
            Integer next = iterator.next();
            System.out.println(next);
        }

        System.out.println("---");

        // now loop back to the begin
        while (iterator.hasPrevious()) {
            Integer previous = iterator.previous();
            System.out.println(previous);
        }

    }

}

Output


1
2
3
4
5
---
5
4
3
2
1

2.3 Update elements with ListIterator.set()

JavaIteratorExample2c.java

package com.mkyong;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class JavaIteratorExample2c {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        ListIterator<Integer> iterator = list.listIterator();

        while (iterator.hasNext()) {
            Integer next = iterator.next();
            if (next == 3) {
                iterator.set(33);
            }
            if (next == 4) {
                iterator.set(44);
            }
        }

        list.forEach(x -> System.out.println(x));
    }

}

Output


1
2
33  // updated, was 3
44  // updated, was 4
5

2.4 Add elements with ListIterator.add()

JavaIteratorExample2d.java

package com.mkyong;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class JavaIteratorExample2d {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        ListIterator<Integer> iterator = list.listIterator();

        while (iterator.hasNext()) {
            Integer next = iterator.next();
            if (next == 5) {
                iterator.add(6);
            }
        }

        list.forEach(x -> System.out.println(x));
    }

}

Output


1
2
3
4
5
6  // new!

2.4 Get the iterator’s current position, previousIndex() and nextIndex()

JavaIteratorExample2c.java

package com.mkyong;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class JavaIteratorExample2c {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        ListIterator<Integer> iterator = list.listIterator();

        while (iterator.hasNext()) {

            // cursor index, iterator not move yet!
            // init = -1 , add 0
            if (iterator.previousIndex() < 0) {
                iterator.add(0);
            }

            // move the iterator
            iterator.next();

            // if this is last index
            if (iterator.nextIndex() >= list.size()) {
                iterator.add(6);
            }

        }

        list.forEach(x -> System.out.println(x));
    }

}

Output


0
1
2
3
4
5
6

3. Convert Iterator to Stream

Follow steps Iterator -> Spliterators -> Stream -> List

JavaIteratorExample3a.java

package com.mkyong;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public class JavaIteratorExample3a {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        Iterator<Integer> iterator = list.iterator();

        // Iterator -> Spliterators -> Stream -> List
        List<Integer> result = StreamSupport.stream(
                Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
                .map(x -> x * 2)
                .collect(Collectors.toList());

        result.forEach(x -> System.out.println(x));
        System.out.println(result.getClass());

    }

}

Output


2
4
6
8
10
class java.util.ArrayList

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar