Reactive programming with Java 8 and simple-react : filter / map / reduce & flatMap

John McClean
2 min readMar 25, 2015

--

A pretty common combination in Stream processing is filtering some data before transforming it (mapping) to a different type and reducing the complete dataset to a single result.

Example: To load user data from a database and total the number of visits by users who have bought something.

LazyFutureStream.sequentialBuilder()
.react(()->loadUserData())
.forEach(System.out::println);

Now we have a collection of data with all users in it. Let’s flatten it (rather than processing the collection, we’ll pass the individual elements of that collection to the next stage). And we can do that with the flatMap operator, and by creating a function that returns a Stream. In this case we’ll Stream out the Collection that comes in as a parameter from the last stage (loadUserData() returns a collection of users).

flatMap!

LazyFutureStream.sequentialBuilder()
.react(()->loadUserData())
.flatMap(Collection::stream)
.forEach(System.out::println);

map!

Now let’s get the number of visits for each user, by transforming the User objects in the Stream into Integers (where the value is the number of visits).

LazyFutureStream.sequentialBuilder()
.react(()->loadUserData())
.flatMap(Collection::stream)
.map(User::getTotalVisits)
.forEach(System.out::println);

filter!

We only need the totals for the users that have bought something, so we need to filter the Stream of users before we convert them into a Stream of visits.

LazyFutureStream.sequentialBuilder()
.react(()->loadUserData())
.flatMap(Collection::stream)
.filter(User::hasPurchased)
.map(User::getTotalVisits)
.forEach(System.out::println);

reduce!

We would like to total the number of visits across all Users, reducing the dataset to a single value.

int total = LazyFutureStream.sequentialBuilder()
.react(()->loadUserData())
.flatMap(Collection::stream)
.filter(User::hasPurchased)
.map(User::getTotalVisits)
.reduce(0,acc,next -> acc+next);
System.out.println("total is : " + total);

The Tutorial : Reactive programming with Java 8

--

--

John McClean

Architecture @ Verizon Media. Maintainer of Cyclops. Twitter @johnmcclean_ie