Streams in Java 8
04 Feb 2017The functional programming paradigm has certainly seen a lot of attention of late, where some of the features that can be exploited from it have properties that assist in scale programming.
In today’s post, I’ll walk through Java 8 streams which allow you to treat collection data structures in a functional way.
What is a stream?
A stream prepares a collection of elements in such a way that you can operate on it functionally. The higher-order functions that you’d commonly see in a functional arrangement are:
An example
To start with, we need to define some test data. We’re going to work with artists and songs:
Now that we have a basic structure of artists and songs, we can define some test data to work with.
Don’t judge me.
Ok, now that the boilerplate is out of the way; we can start the fun stuff.
Map
map is a function that allows you to apply a function to each element of a list; transforming and returning it. We can grab just the artist’s names with the following:
toList
comes out of the java.util.stream.Collectors
class. So you can import static
:
Mapping deeper
flatMap
allows you to perform the map
process on arrays of arrays. Each artist has an array of songs, so we can flat map (at the artist level) to emit a flat list of songs:
Filter
We only want artists over the age of 52.
Reduce
We can aggregate all of the sales figures into a single value:
Ok, so this has been a whirlwind tour of the Java 8 functional interface.