8

Does java8 forEach method use an iterator or not really? I google it to the bone, could not find it precisely. Only the fact that it will iterate in the same order the data are.

Any tips?

dimo414
  • 47,227
  • 18
  • 148
  • 244
Rollerball
  • 12,618
  • 23
  • 92
  • 161

1 Answers1

11

The default implementation of Iterable#forEach is based on a iterator.

    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }

But in ArrayList is overridden to this, and not uses the iterator, it uses a for loop over its internal array

    @Override
    public void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

So it depends of its implementation.

Anyway, since this method is declared in Iterable interface, all iterables has this method.

Rollerball
  • 12,618
  • 23
  • 92
  • 161
Ezequiel
  • 3,477
  • 1
  • 20
  • 28
  • 1
    additionally : clients should not rely on any `Iterable` implementation to use the underlying `Iterator`. Even when the current implementation does, future versions may not. – bowmore May 19 '15 at 16:49
  • 1
    Since the caller does not know whether `forEach` will use an `Iterator` or not, it is an “internal iteration” as that’s the whole point: the way, how the iteration is implemented, is hidden *within* the actual `forEach` implementation. – Holger May 20 '15 at 09:07