Lesson 20Stream API

In this lesson you’ll learn how to work with the new Stream application programming interface (API) introduced in Java 8 (not to be confused with I/O Streams). Stream API enables you to write data processing in a simpler and more understandable way.  Most of the examples in this chapter illustrate iterating and manipulating data from Java collections, but you should know from the very start that the Stream API is not just another type of a data collection. It’s an abstraction over a bunch of data that your program needs to process. 

The data can come from a collection, from some function that generates data, or from an I/O stream. Using the Stream API and lambda expressions, you can write simple-to-read and efficient iterators that will result in a subset of the incoming data or some kind of a data aggregation.

All new classes and interfaces supporting the Stream API are located in the package java.util.stream, and the Stream interface is the main player there. Some old classes (for example, BufferedReader) located in other packages now include new methods returning the reference to its data as a Stream.

Stream Basics

A stream is an abstraction that represents zero or more values. Think of it as a fancy iterator that enables you to declare one or more operations on the data and then perform these operations in one pass. But whereas a regular Java Iterator works sequentially, streams can also be processed in parallel. 

Let’s start with a simple example. ...

Get Java Programming 24-Hour Trainer, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.