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);
}
}**