Stream API

A Stream in the new Java 8 is a typed interface, where we can use a Stream of T elements, being T an integer, a String, an Employer object, etc.

With Stream we can handle data the same way we would work in a Big Data environment, applying map-filter-reduce operations, for example.

But aware you must! a Stream may look like a Collection at first sight, but it is NOT a collection. I repeat. It is not a collection. Collections and Streams work in a total different way. In fact, a Stream object does not store any info, unlike a Collection.

List<String> employees = Arrays
                .asList( "John \"Hannibal\" Smith ", 
                         "Templeton Peck", 
                         " H.M. \"Howling Mad\" Murdock", 
                         "\"Bad Attitude\", Baracus " ); 

//We want all items that start with T 
employees 
   .stream() 
   .filter(s -> s.startsWith("T")) 
   .forEach(e -> System.out.println(e)); 

//But at the end, the employees list remains intact 
System.out.println(employees.size());

  If we execute this code, we would get the following console output.

Templeton Peck

4

One of the most interesting features of this Stream interface is the fact that it will work in parallel, meaning, will use all processors we may have in our machine, avoiding the programmer to handle this work for him, in a total transparent way.

Filtering

What we have done in the last piece of code was a nice filter. Filtering data with Streams is fairly simple. In the following example, we want to get all the employees that contains the word 'Attitude'

Stream streamEmployees = listEmployees.stream();

Stream  employeesFiltered = streamEmployees.filter(s -> s.contains("Attitude"));

employeesFiltered.forEach(s -> System.out.println(s));

In this case we would get what we were searching for:

"Bad Attitude", Baracus

There is something very important to remember when we work with Streams. Once we have used a Stream, it cannot be reused, or we will have a nice exception in our console. Hence, if we try to apply the forEach method again:

employeesFiltered.forEach(s -> System.out.println(s));

We will get this message in our console:

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed

at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:229)

at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)

at com.sergiolealdev.java8.streams.Main.main(Main.java:33)

This is it for the first part of the new features in Java8. New posts arriving soon!!

github_24px Watch/Download this code in Github