Nick Fisher's tech blog

Java Stream Api

Java IO: Paths and Files

The sample code for this repository can be found on Github.

System paths and file manipulation, usually within the java.nio package, in Java allow you to forgo some of the details related to streaming of files–which, while they offer low level details and optimization opportunities, typically take longer to develop and get right.

The Java Stream API: Primitive Streams

The sample code for this post can be found on GitHub.

While Streams in Java would typically be used on POJO or POJO-like data structures, Java also lets us deal directly with primitive type streams. Thanks to Java’s type erasure, something like Stream would not work, as the type argument must be an Object.

The Java Stream API: Collecting Downstream Elements

You can view the sample code associated with this post on GitHub.

One interesting feature of collecting streams using the Collectors.groupingBy(..) method is the ability to manipulate downstream elements. Basically, this means that, after you group the keys of the map, you can further make changes to the collection that the map is pointing to. By default, it collects to a list.

The Java Stream API: Collecting Into Maps

You can view the sample code associated with this post on GitHub.

Taking a stream of POJOs and transforming it into a map is one of the more common uses of Streams. There are a few built in ways to get what you want. The simplest way to map one field to another in a POJO is by using the .toMap(..) method.

The Java Stream API: An Introduction to Collecting Results

You can view the sample code associated with this post on GitHub.

Calling collect(..) on a stream terminates a stream into a collection. We’ve already seen that calling collect(Collectors.toList()) moves your stream into a List, but you can also collect into a set. If we take our familiar collection of names in a String collection:

The Java Stream API: Creating Optional Types

You can view the sample code associated with this post on GitHub.

While Optionals are often used in conjunction with the Java Stream API, you can also create your own. Now, why would you want to do that? Simply put, null pointer exceptions are not a fun time, and embracing optional types will greatly simplify code development, and prevent premature graying hair.

The Java Stream API: Generating Fibonacci Numbers

You can find the sample code for this post on GitHub.

From the knowledge gained via creating custom Java Stream objects, we can start to have a little bit of fun with this. The fibonacci number sequence starts with [0, 1], and adds each of the previous two elements to create the next element in the sequence. This looks like [0, 1, 1, 2, 3, 5, 8, 13, 21…], and goes on “forever.” We can thus create a template that computes all Fibonacci numbers by implementing a Supplier. like so: