forEach() method in Iterable Interface:
Java 8 has introduced forEach method in java.lang.Iterable interface so that while writing code we focus on business logic only. forEach() method takes java.util.function.Consumer object as argument, so it helps in having our business logic at a separate location that we can reuse.
Example Showing forEach() method In Iterable Interface:
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class ForEachWithIterator {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for(int i=0;i<10;i++){
list.add(i);
}
System.out.println("Traversing list through forEach() method of iterable with ananomous class");
list.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
System.out.print(t+",");
}
});
System.out.println("\n\nTraversing list through forEach() method of iterable with interface");
MyConsumer action = new MyConsumer();
list.forEach(action);
}
}
class MyConsumer implements Consumer<Integer>{
@Override
public void accept(Integer t) {
System.out.print(t+",");
}
}
Program Output:
Traversing list through forEach() method of iterable with ananomous class
0,1,2,3,4,5,6,7,8,9,
Traversing list through forEach() method of iterable with interface
0,1,2,3,4,5,6,7,8,9,
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.
This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.
This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.
Java I/O Tutorial


No comments:
Post a Comment