Functional Programming - flatMap

Imperative Vs Functional

About

This is when the element that you get in the stream is a list. You can flatten this list of list in a list of element. You do that with a flatMap operations.

The flatMap operation produces any number of output values per input value – include zero

The flatMap() operation has the effect of applying a one-to-many transformation to the elements of the stream (a list of list will create one big list), and then flattening the resulting elements into a new stream.

Example

A table may have several foreigns key. If we have several tables and that we want a list of all foreigns keys, we need flatMap to go from a list of foreign key by table to a list of keys for all tables.

Java

In Java, you need to return a stream with Stream.of of the stream method of any collections.

 
List<ForeignKey> foreignKeys = tables
            .stream()
            .flatMap(s->s.getForeignKeys().stream())
            .collect(Collectors.toList());





Discover More
Imperative Vs Functional
Code - Functional programming (FP) - Collection Operations

Functional programming (FP) defines standard operations on collections. It is a declarative paradigm that treats computation as the evaluation of mathematical functions. Most of the operations, you perform...



Share this page:
Follow us:
Task Runner