1. Inroduction

1.1 Lambdas and (Parallel) Streams

Some of the new features introduced in Java 8, like the new Date and Time API, feel quite familiar and can be used immediately by an experienced Java developer. But some of the most important enhancements, including Lambdas and Streams, require the developer to learn some new concepts. Lambda statements in particular introduce a syntax which is quite unusual for object oriented programmers. These language constructs are known only to developers who used functional programming languages or enhancements like Microsoft’s Linq. This special syntax takes some getting used to and some developers may even be a little frightened at first glance. However, these enhancements are extremely powerful and it is certainly worth taking the time to understand how they can help you to write code that is not only concise, but also faster to write and more re-usable.

This book starts with an explanation of Lambda expressions, shows how they can be used with Streams and finally discusses how both Lambdas and Streams can be combined to implement effective parallel processing.

The following task will run like a golden thread through the book:

1.2 The challenge

  • Analyze a bigger amount of data according to varying criteria
  • Parallelize this task without explicit use of thread management, synchronization, Excecutor or ForkJoin

1.3 The solution

Use parallelStream() instead of stream()!

1.4 A first explanation

You may well ask “what the hell are the stream() and parallelStream() methods?” Here is the quick overview; a more detailed description is given in later chapters.

You may imagine a Stream as a continuous flow of data, comparable to something like an InputStream. The data might be emitted by different sources, like a collection, a file, a generator, or some other source. However, the content of this stream is not simply bytes or characters; instead the stream emits arbitrary objects.

 
Stream (Quelle is German for source)
Stream (Quelle is German for source)
 

On their journey from source to target, the objects may be filtered, changed, transformed, collected or processed in some other way. How and with whichever means this happen will be described later on.

A ParallelStream can be imagined as a parallel stream of objects of the same type. The objects are split into different streams at their source. Later on, we will discuss the details of this splitting task.

 
Parallel Streams
Parallel Streams
 

To implement solutions to our challenge we will use some of Java’s new language features including:

  • Lambda statements
  • Functional Interfaces
  • Default methods
  • Optionals
  • Streams
  • Operations on streams