Home > Articles > Web Development

Java SE 8's New Streams API

📄 Contents

  1. Introducing the Streams API
  2. Exploring Streams API Operations
Java is evolving to support parallel programming on multicore processors. For example, Java SE 7 introduced the Fork/Join Framework. Because the Collections Framework isn't amenable to parallelism, Java SE 8 introduced the Streams API to bring parallelism to Collections, as well as to arrays and other sources. In this article, Jeff Friesen introduces you to the Streams API.
Like this article? We recommend

Java SE 8 strengthens the Java language by introducing lambda expressions and additional language features. Although lambdas help you write functional code that's more compact than the anonymous class equivalent, they more importantly facilitate parallel processing in the context of the Java SE 8 Streams API.

To learn about lambdas, check out my article Java SE 8's New Language Features, Part 1: Interface Default/Static Methods and Lambda Expressions.

In this article, I first introduce you to the Streams API, where you learn about API fundamentals, receive an overview of key types, and discover the need for this API. Then we explore various API operations that you can perform on stream sources; for example, performing actions on all stream elements, filtering, mapping, and reduction.

I developed this article's applications with the 64-bit version of JDK 8 build 132 on a Windows 7 platform. You can download the code from this article here.

Introducing the Streams API

The Streams API facilitates the processing of data items sequentially or in parallel. This section first explores several fundamentals on which this API is based; for example, what is a stream, and what is a source? Next, I present an overview of the Streams API in terms of package and key types. Finally, we examine the need for streams.

Streams API Fundamentals

The Streams API is based on the concept of a stream, which is a sequence of elements originating from a source and supporting sequential and parallel aggregate operations. A source is an entity that stores elements (for example, a collection) or generates elements (such as a random number generator). An aggregate is a single result calculated from multiple input values.

Streams support various operations that are either intermediate or terminal. An intermediate operation returns a new stream, whereas a terminal operation consumes the stream. Operations are connected into a pipeline, which starts with a source followed by zero or more intermediate operations and ending with a terminal operation. Figure 1 illustrates this arrangement.

Figure 1 A pipeline of operations in which an intermediate operation's output becomes the input to the next operation

Intermediate operations are always lazy in that they don't do anything until a terminal operation is executed. Instead, an intermediate operation returns a new stream that is traversed after the pipeline's terminal operation is executed. Note that an intermediate operation doesn't have to finish before its output becomes available to the next operation in the pipeline.

Intermediate operations are classified as stateless and stateful. Stateless operations retain no state from a previously seen element when processing a new element. Each element can be processed independently of operations on other elements. Stateful operations may incorporate state from previously seen elements when processing new elements.

Terminal operations may traverse the stream to produce a side-effect or result. A side-effect is the execution of a code block. Although side-effects are generally discouraged because they can often lead to thread-safety hazards, some side-effects (such as printing elements for debugging purposes) are typically harmless.

After a terminal operation completes, the pipeline is considered to be consumed and no longer can be used. To traverse the same source again, you must obtain a new stream from the source. In most cases, terminal operations are eager in that they complete their source traversal and pipeline processing before returning.

Some operations are classified as short-circuiting. An intermediate operation is short-circuiting if it produces a finite stream when presented with infinite input. A terminal operation is short-circuiting if it terminates in finite time when presented with infinite input. Having a short-circuiting operation in the pipeline is a necessary (but not sufficient) condition for processing an infinite stream to terminate normally in finite time.

Some streams have a defined encounter order that specifies the order in which elements are returned. Whether a stream has an encounter order depends on its source and intermediate operations. Stream sources such as java.util.List and arrays are intrinsically ordered, whereas sources such as java.util.HashSet are not.

Some intermediate operations may impose an encounter order on an otherwise unordered stream, whereas other intermediate operations may return an unordered stream for an ordered stream. Also, terminal operations might ignore an encounter order. For an ordered stream, most operations are constrained to operate on the elements in their encounter order.

Streams API Overview

The Streams API is associated with the java.util.stream package. This package consists of two classes, one enum, and several interfaces, with BaseStream<T,S extends BaseStream<T,S>> being the fundamental stream interface that's extended by the following interfaces:

  • Stream<T>: A sequence of object elements of type T supporting sequential and parallel aggregate operations.
  • DoubleStream: A sequence of primitive double-valued elements supporting sequential and parallel aggregate operations. This is the double primitive specialization of Stream.
  • IntStream: A sequence of primitive int-valued elements supporting sequential and parallel aggregate operations. This is the int primitive specialization of Stream.
  • LongStream: A sequence of primitive long-valued elements supporting sequential and parallel aggregate operations. This is the long primitive specialization of Stream.

Stream<T> describes streams of objects (of type T). Although you can use this interface to describe streams of ints, longs, and doubles, doing so isn't efficient because of the need for autoboxing and unboxing (and java.lang.Double, java.lang.Integer, and java.lang.Long wrapper objects created behind the scenes). This is the reason for DoubleStream, IntStream, and LongStream.

Java provides various ways to obtain a BaseStream from collections and other sources:

  • From a collection via java.util.Collection's Stream<E> stream() (return a sequential stream) and Stream<E> parallelStream() (return a parallel stream—a sequential stream might be returned) default methods.
  • From an array via the various stream() methods of the java.util.Arrays class.
  • From static factory methods on the stream classes, such as <T> Stream<T> of(T t), IntStream range(int startInclusive, int endExclusive), and <T> Stream<T> iterate(T seed, UnaryOperator<T> f).
  • From java.io.BufferedReader's Stream<String> lines() method.
  • From java.nio.file.Files methods such as Stream<String> lines(Path path).
  • From a stream of random numbers generated by java.util.Random methods such as IntStream ints().
  • From additional JDK stream-oriented methods such as java.util.BitSet's IntStream stream() and java.util.regex.Pattern's Stream<String> splitAsStream(CharSequence input).

Additionally, stream sources can be provided by third-party libraries.

The Need for Streams

Multicore processors have raised awareness of parallelism, which is the ability to execute multiple tasks at the same time, greatly improving performance. The introduction of the Fork/Join Framework in Java SE 7 gave Java developers the ability to start leveraging parallelism in their applications. But this was only the beginning.

The Java Collections Framework was introduced (as part of JDK 1.2) before today's emphasis on parallelism. Although this framework could benefit from leveraging multicore processors, it isn't amenable to parallelism. A significant impediment is the need to use external iteration to retrieve objects from a collection. The following example demonstrates external iteration:

List<String> birds = Arrays.asList("Robin", "Bluejay", "Penguin",
                                   "Ostrich", "Canary");
// Employ external iteration.
for (String bird: birds)
   System.out.println(bird);

This example creates a list of strings, using the enhanced for loop statement to iterate over this list and subsequently output each object's string representation on its own line. Although external iteration is easy to specify, it's problematic for the following reasons:

  • It's inherently sequential. External iteration is sequential and must process the elements in the order that the collection specifies. Significant refactoring would be required to leverage parallelism and improve performance, especially for huge collections.
  • It's client-centric. External iteration is part of client code and not part of a library. If the code was generalized and stored in a library, you might have opportunities to exploit parallelism and other features that improve performance. As it stands, you would have to refactor the code and develop a library that hides the iteration and provides you with these performance-improvement opportunities. This isn't an easy task if you're unfamiliar with Fork/Join, which you would probably use to exploit parallelism. Also, a redeployment of the code might prove costly or otherwise problematic.

Ideally, Collections Framework types should support internal iteration that can exploit parallelism and other performance-enhancing features. Because introducing this capability would break legacy code, Java SE 8 introduced the Streams API (and lambdas) and enhanced the Collection interface with stream() and parallelStream() default methods to make the Collections Framework parallel-friendly.

The following example demonstrates internal iteration in sequential and parallel contexts, contrasting the previous example's verbosity with Streams API/lambda elegance:

// Employ internal iteration.
birds.stream().forEach(System.out::println);
birds.parallelStream().forEach(System.out::println);

I first invoke stream() or parallelStream() on birds to obtain a stream for the list. I then invoke forEach() on the resulting stream to iterate over the list objects. I pass a System.out::println method reference (a compact representation of a lambda) argument to forEach(), which it executes to output the object. (The output order of a parallel stream will probably differ from that of a sequential stream.)

You might be tempted to view a stream as a collection. However, streams differ from collections in the following (and other) ways:

  • Lack of storage. A stream isn't a data structure that stores or generates elements. Instead, a stream transports elements from a collection or other source that stores or generates elements.
  • Tendency to be lazy. Many stream operations (such as filtering) are or can be implemented lazily, which exposes optimization opportunities. For example, a "Find the first String starting with the letter J" stream operation doesn't have to examine all input strings. In contrast, collection iteration is always eager, returning every element.
  • Potentially unbounded. Collections have a finite size, but streams don't need to be finite and are often referred to as infinite streams. Various operations can allow computations on infinite streams to complete in finite time.

Finally, although the Streams API is largely present to make the Collections Framework parallel-friendly, this isn't its only reason for existence. As you've previously learned, other entities (such as arrays) can serve as stream sources. There is definitely a need for the Streams API.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020