Skip to main content

How do I add elements while iterating over a List

In this Q&A, we'll go over how to perform collection mutating operation(s) when iterating over it.

Iterator interface does not support adding elements to the collection.  You can add/remove elements using a list iterator.  Note that the iterator will not iterate over the added elements

See this example below

    public static void iteratorAdd() {
        List<Integer> l = new LinkedList<>();
        for( int i =0; i < 100; ++i)
            l.add(i);

        ListIterator<Integer> li = l.listIterator();

        while(li.hasNext()) {
            li.add(li.next() + 100);
        }
        l.forEach((x)->System.out.println(x));
    }

Comments