Java 8 forEach examples

Java 8 forEach example

In this post, we will see improved way of iterating through map and list which are introduced in java 8.

Map:

Normal way of iterating HashMap before java 8:

Improved way of iterating HashMap in java 8:

When you run above program, you will get below output:

Iterating Using Java 8
—————————–
Country:Japan Capital : Tokyo
Country:France Capital : Paris
Country:India Capital : Delhi
Country:Russia Capital : Moscow
—————————–

List:

Normal way of iterating list:

Iterating through list in java 8:

forEach method internally use Consumer Object.You can read more about Java 8 Consumer interface.

Arpit John Martin Adam

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *