How to use Java 8 Stream FlatMap Examples with List, Array

java-8-stream-flat-map-api-examples


In the tutorial, we will discover more aspect of Java 8 Stream API with flatMap() function by lots of examples.
What we will do:

  • Explain how Java 8 Stream FlatMap work?
  • Apply Stream FlatMap on Java List, Array

Now let’s do more details!

Related posts:
Java 8 Stream Map Examples
Java 8 Stream Filter Examples

Java 8 Stream FlatMap

Java 8 Stream provides 2 mapping APIs: map() and flatMap()

– Both map() & flatMap() is an intermediate operation.
– Stream map() function is used to transform an input stream to a new output stream by applying a mapper function on each element.
-> What is a difference point with Stream flatMap() function?

The flatMap() function will do 2 things:
– Apply mapper function to transform each element of input stream.
– Then flattens the result to a new output stream. (Not with Java 8 Stream map() function)

Stream FlatMap Java List Example

Stream FlatMap Integer List Example

We do a list of examples about Stream flatMap() function combining with others: map(), filter(), reduce()

Example 1 – Flatten Map

Example:

– Code:

Example 2 – Combine flatMap() with map()

Example 2:

Code:

Example 3 – Combine flatMap() with reduce()

Example:

Code:

Example 4 – Combine flatMap() with filter()

Example:

Code:

Stream FlatMap String List Example

Example:

Code:

Stream FlatMap Custom Object List Example

– Create Developer class object:

– Using Stream flatMap() combine with distinct() method to get all difference skill set of a List Developers.

Example:

Code:

Stream FlatMap Java Array Example

To apply Stream FlatMap in Array with Java 8, We do 2 steps:

  • Create Stream from Array Objects.
  • Apply Stream FlatMap for Array Objects as the same way we had done with above List Objects.

– Modify Customer class:

– Stream FlatMap Example with Java Array:

Conclusion

We had learned Java 8 Stream FlatMap with examples:

  • Apply Java 8 Stream FlatMap to Integer, String and Custom Object List
  • Combine Stream flatMap() function with others: map(), reduce(), filter(), distinct()
  • Apply Stream FlatMap to Java Array

Thanks for reading! See you later!

By grokonez | April 8, 2019.



Related Posts


Got Something To Say:

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

*