Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java 8 introduces iterable.forEach() loop even though it has for each?

I'm not able to understand why java 8 has forEach loop and taking the Consumer functional interface as parameter. Even though we can do the same task using traditional for each loop without creating any extra overhead to create a class implements that from Consumer and implements a method and then pass this as reference to the forEach(). Although there is lambda expression to make it short.

Q1- why iterable.forEach()?

Q2. Where to use it?

Q3. which one is faster traditional for each of Java 8 forEach()?

Sample:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
import java.lang.Integer;

public class ForEachExample {

    public static void main(String[] args) {

        //creating sample Collection
        List<Integer> myList = new ArrayList<Integer>();
        for(int i=0; i<10; i++) myList.add(i);

        //traversing using Iterator
        Iterator<Integer> it = myList.iterator();
        while(it.hasNext()){
            Integer i = it.next();
            System.out.println("Iterator Value::"+i);
        }

        //traversing through forEach method of Iterable with anonymous class
        myList.forEach(new Consumer<Integer>() {

            public void accept(Integer t) {
                System.out.println("forEach anonymous class Value::"+t);
            }

        });

        //traversing with Consumer interface implementation
        MyConsumer action = new MyConsumer();
        myList.forEach(action);

    }

}

//Consumer implementation that can be reused
**class MyConsumer implements Consumer<Integer>{
    public void accept(Integer t) {
        System.out.println("Consumer impl Value::"+t);
    }
}**
like image 268
Pravin Mangalam Avatar asked Jun 25 '18 04:06

Pravin Mangalam


2 Answers

The general idea of the new APIs inspired by Functional Programming is to express what to do instead of how to do it. Even when using the simplified for-each loop,

for(Integer i: myList) System.out.println("Value::"+i);

it’s just syntactic sugar for the instructions “acquire an Iterator instance and call repeatedly hasNext() and next() on it”.

In contrast, when using

myList.forEach(i -> System.out.println("Value::"+i));

you provide an action, to be applied to each element, but don’t specify how to do it. The default implementation will just perform the Iterator based loop, but actual Iterable implementations may override it to perform the operation differently.

Note that a lot of Iterator implementations are performing checks twice, once in hasNext(), then again in next() as there is no guaranty that the caller did hasNext() first, to throw a NoSuchElementException if there is no next element. Sometimes this even implies holding additional state within the Iterator instance to remember whether a particular “fetch-next” operation has been performed already. A dedicated forEach implementation can be straight-forward, more efficient while being simpler in code.

For example, ArrayList performs an int-index based loop without constructing an Iterator instance, Collections.emptyList() does nothing but checking the Consumer against null, TreeSet resp. its backing TreeMap traverses entry links, which is much simpler than its Iterator implementation which has to support the remove operation, and so on.

Whether a dedicated forEach implementation may compensate the Consumer construction related overhead, if there is one (mind that not every lambda expression creates a new object), is not predictable and assumptions about that should not drive the software design. More than often, the performance differences are negligible.

But there can be semantic differences too. When using one of the collections returned by Collections.synchronized…, an Iterator based loop can not provide consistency guarantees when the underlying collection is modified by another thread. The application would need to lock on the collection manually and have to care to use the right object instance, e.g. if the iterable is a subList or subSet. In contrast, the specialized forEach(Consumer) locks correctly during the entire operation, whereas the operation itself is as simple as delegating to the source’s forEach method, to still perform it in the optimal way according to the actual underlying collection.

like image 80
Holger Avatar answered Jan 02 '23 20:01

Holger


It just a tasty problem. If you want something more functional, use forEach, but in your case, the traditional for-each loop is good. In fact, there are two things for-loop supports but forEach not:

  1. flow control keywords like continue, break, return
  2. Checked exception
like image 22
a.l. Avatar answered Jan 02 '23 21:01

a.l.