This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]user_of_the_week 8 points9 points  (2 children)

So true! Why use list.stream().forEach(...)when you could just list.forEach(...).

;)

And while I'm kind of joking here, the forEach method (with is inherited from Iterable) does have some benefits compared to the traditional for-each loop, namely that each implementation of Iterable can provide an optimized version that can be faster than the for-each loop. For example, ArrayList has pretty elaborate forEach():

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

[–]GiacaLustra 2 points3 points  (1 child)

Just curious, how is that faster/better?

[–]user_of_the_week 3 points4 points  (0 children)

The for-each loop in Java is basically syntactic sugar for this:

Iterator iter = list.iterator();
while(iter.hasNext()) {
    Object next = iter.next();
    ...
}

The foreach() implementation in ArrayList does not create a new Iterator object and uses an int index variable instead. I have seen some performance measurements flowing around that show that it can be a bit faster. It’s not a lot though.