Java 8 forEach – with Iterable (List + Map) and Stream

In the tutorial, we show how to use Java 8 forEach() method with Iterable (List + Map) and Stream.

I. Java 8 – forEach

1. forEach()

In Java 8, Iterable and Stream Interfaces provides a new method forEach() to iterate the elements.

2. How to use it?
2.1 Functional Interface Consumer

To use Java 8 forEach() method, we need defined a Functional Interface Consumer:

#1 -> create Functional Interface Consumer by anonymous inner class

#2 -> Use Lambda Expression to create Functional Interface Consumer

2.2 Lambda Expression + Method Reference

We can use shortcut syntax with Lambda Expression and Method Reference:

-> Use Lambda expression

-> Use Method Reference:

If Customer class define a show() method, we can use it with Method Reference:

3. Java 8 forEach() with break + continue

forEach does not work with break statement. But we can use return statement like a continue in a for-each.

4. Java 8 forEach() with Stream
4.1 List -> Stream -> forEach()

4.2 Map -> Stream -> forEach()

II. SourceCode

1. Data models

2. Java 8 forEach() with List + Stream

3. Java 8 forEach() with Map + Stream

By JavaSampleApproach | March 3, 2018.

Related Posts


Got Something To Say:

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

*