Java 8 forEach examples

In this tutorial we will show you how to use Java 8 forEach method, this new approach give you a more concise way to iterate over a collection. In this post we will provide examples for using the forEach method with a Java List and also with a Java Map

Looping through a list before Java 8:

Below is an example of how to iterate through a list without using the new forEach method.

Java 8 forEach list example:

The next example repeats the same behaviour as the example above, but this time it is using the new forEach method.

The ‘s’ in the above example is a variable which contains the value of the list element

Output

Running both of the above pieces of code produce the same output however, the new java 8 forEach approach makes things a lot more concise and easier to read.

Looping through a Map before Java 8:

The example below show how to loop through a map before Java 8.

Java 8 forEach Map example:

The following code same shows how to loop through a map using the new forEach method.

The ‘k’ and ‘v’ variables above represent the key and value of the map entry.

Output:

Running both of the examples produces the same result however, as you can see the new Java 8 forEach method makes things a lot more concise and simpler.

In conclusion I hope you found this post useful and helped you better understand how to use the forEach method.

Similar posts:

  1. How to parse a JSON array into a List with GSON
  2. How to convert JSON string to a Java object
  3. How to read a file in Java

References:

  1. Java 8 documentation

 

Leave a Reply

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