How can process collections easily with Stream in Java 8.

How can process collections easily with Stream in Java 8.

In this tutorial, we learn how to use Streams to easily process collections in Java 8, looking specifically at characteristics, advantages...

In Java, collections and arrays are two common data structures, on which many operations are regularly performed, including addition, deletion, modification, query, aggregate, statistics, and filtering. These operations also exist in relational databases. However, it is not very convenient to process collections and arrays before Java 8.

This problem is greatly alleviated in Java 8 by introducing a new abstraction called Stream API, which allows us to process data in a declarative manner. This article shows how to use Stream. Note that the performance and principles of Stream are not the central part of this article.

Stream Introduction

Stream provides a high-level abstraction for Java collection operations and expressions by querying data from databases similar to SQL statements.

Stream API can significantly improve the productivity of Java programmers and allow them write effective, clean, and concise code.

A collection of elements to be processed are considered as a stream, which is transmitted in a pipeline. These elements can be processed on nodes of the pipeline, such as filter, sort, and aggregate.

Characteristics and Advantages of Java Streams:

  • No storage. A Stream is not a data structure, but only a view of a data source, which can be an array, a Java container or an I/O channel.
  • A Stream is functional in nature. Any modifications to a Stream will not change the data sources. For example, filtering a Stream does not delete filtered elements, but generates a new Stream that does not contain filtered elements.
  • Lazy execution. Operations on a Stream will not be executed immediately. They will be executed only when users really need results.
  • Consumable. The elements of a stream are only visited once during the life of a stream. Once traversed, a Stream is invalidated, just like a container iterator. You have to regenerate a new Stream if you want to traverse the Stream again.

Let's use an example to see what a Stream can do:

The preceding example gets some plastic balls as the data source, filters the red ones, melts them down and converts them into random triangles. Another filter removes small triangles. A reducer sums up the circumferences

As shown in the preceding figure, a Stream involves three critical operations: stream creation, intermediate operations and terminal operations.

Stream Creation

In Java 8, many methods can be used to create a Stream.

1. Create a Stream by Using Existing Collections

In addition to many stream-related classes, Java 8 also enhances the collection class itself. The stream method in Java 8 can convert a collection into a Stream.

List<String> strings = Arrays.asList("Hollis", "HollisChuang", "hollis", "Hello", "HelloWorld", "Hollis");
Stream<String> stream =;

The preceding example creates a Stream from an existing List. In addition, the parallelStream method can create a parallel stream for a collection.

It is also very common to create a Stream from a collection.

2. Create a Stream by Using the Stream Method

The of method provided by Stream can be used to directly return a Stream consisting of specified elements.

Stream<String> stream = Stream.of("Hollis", "HollisChuang", "hollis", "Hello", "HelloWorld", "Hollis");

The preceding code creates and returns a Stream by using the of method.

Stream Intermediate Operations

A Stream may have many intermediate operations, which can be combined to form a pipeline. Each intermediate operation is like a worker on the pipeline. Each worker can process the Stream. intermediate operations return a new Stream.

The following is a list of common intermediate operations:


The filter method is used to filter elements by specified conditions. The following code snippet uses the filter method to filter empty strings:

List<String> strings = Arrays.asList("Hollis", "", "HollisChuang", "H", "hollis"); -> ! string.isEmpty()).forEach(System.out::println);
//Hollis, , HollisChuang, H, hollis


The map method maps each elements to its corresponding result. The following code snippet use the map method to generate the square numbers of corresponding elements:

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); i -> i*i).forEach(System.out::println);


Limit returns the first N elements in a Stream. Skip abandons the first N elements in a Stream. The following code snippet uses the limit method to retain the first four elements:

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);;


The sorted method sorts elements in a Stream. The following code snippet uses the sorted method to sort Stream elements:

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);;


The distinct method is used to remove duplicates. The following code snippet uses the distinct method to deduplicate elements:

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);;

Next, we use an example and a figure to show what will happen to a Stream after performing operations filter, map, sort, limit, and distinct.

The following is the code:

List<String> strings = Arrays.asList("Hollis", "HollisChuang", "hollis", "Hello", "HelloWorld", "Hollis"); 
Stream s = -> string.length()<= 6).map(String::length).sorted().limit(3)

The following figure shows steps and the result for each step.

Stream Terminal Operations

Stream terminal operations also return a Stream. How can we convert a Stream into the desired type? For example, count elements in a Stream and convert that Stream into a collection. To do this, we need terminal operations.

A terminal operation will consume a Stream and generate a final result. That is to say, after a terminal operation is performed on a Stream, the Stream is not reusable and any intermediate operations are not allowed on that Stream. Otherwise, an exception is thrown:

java.lang.IllegalStateException: stream has already been operated upon or closed

This is the same as the meaning of the saying "You cannot step into the same river twice".

The following table lists the common terminal operations.


The forEach method iterates through elements in a Stream. The following code snippet uses forEach to return 10 random numbers:

Random random = new Random();


The count method counts the elements in a Stream.

List<String> strings = Arrays.asList("Hollis", "HollisChuang", "hollis","Hollis666", "Hello", "HelloWorld", "Hollis");


The collect operation is a reduce operation that can accept various parameters and accumulate the stream elements into a summary result:

List<String> strings = Arrays.asList("Hollis", "HollisChuang", "hollis","Hollis666", "Hello", "HelloWorld", "Hollis");
strings  = -> string.startsWith("Hollis")).collect(Collectors.toList());
//Hollis, HollisChuang, Hollis666, Hollis

Next, we still use a figure to show the results of different terminal operations on the Stream given in the preceding example, on which filter, map, sort, limit, and distinct operations have been performed.

The following figure uses an example to show the input and output of all the operations described in this article.


This article explains the use and characteristics of Streams in Java 8. Stream creation, stream intermediate operations, and terminal operations are also described in this article.

We can use two methods to create a Stream: using the stream method of a Collection or using the of method of a Stream.

Stream intermediate operations can process Streams. Both the input and the output of intermediate operations are Streams. Intermediate operations include filter, map, and sort.

Stream terminal operations can convert a Stream into some other container, such as counting elements in a Stream, converting a Stream into a collection and iterating through elements in a Stream.

Thanks for reading ! Originally published on

Further reading

☞ Java Programming Masterclass for Software Developers

☞ Selenium WebDriver with Java -Basics to Advanced+Frameworks

☞ Java In-Depth: Become a Complete Java Engineer!

☞ Top 4 Spring Annotations for Java Developer in 2019

☞ Java Tutorial for Absolute Beginners

☞ 100+ Java Interview Questions and Answers In 2019

☞ Python vs Java: Understand Object Oriented Programming

java api cloud web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer?, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Multi-cloud Spending: 8 Tips To Lower Cost

Mismanagement of multi-cloud expense costs an arm and leg to business and its management has become a major pain point. Here we break down some crucial tips to take some of the management challenges off your plate and help you optimize your cloud spend.

How to Install OpenJDK 11 on CentOS 8

What is OpenJDK? OpenJDk or Open Java Development Kit is a free, open-source framework of the Java Platform, Standard Edition (or Java SE).

A Simple Guide to API Development Tools

APIs can be as simple as 1 endpoint for use by 100s of users or as complex as the AWS APIs with 1000s of endpoints and 100s of thousands of users. Building them can mean spending a couple of hours using a low-code platform or months of work using a multitude of tools. Hosting them can be as simple as using one platform that does everything we need or as complex as setting up and managing ingress control, security, caching, failover, metrics, scaling.

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...