Skip to main content

Java 8 Stream API – Basics

Java 8 introduced a powerful feature called Stream API, found in the package:

import java.util.stream.*;

What is a Stream?​

A Stream is a sequence of elements that supports functional-style operations to process data. It works primarily with collections like List, Set, etc.

Think of a stream as a conveyor belt that allows you to:

  • Filter
  • Transform
  • Collect
  • Iterate
  • Convert data

Why Use Streams?​

  • Removes the need for manual loops
  • Efficient and readable
  • Helps write clean and declarative code
  • Supports parallel processing

Key Difference​

ConceptPurpose
CollectionUsed to store a group of objects
StreamUsed to process those objects

How to Create a Stream​

You can create a stream from a collection like this:

Stream<T> s = collection.stream();
  • collection is any List, Set, etc.
  • .stream() creates a Stream object

Prerequisites​

Before learning Streams, you should be familiar with:

  • Lambda expressions
  • Method references
  • Optional class (introduced in Java 8)

Components of a Stream​

1. Sequence of Elements​

  • A stream works with a sequence of data (like items in a list)

2. Source​

  • The source can be a collection, array, or I/O channel

3. Aggregate Operations​

  • Operations like filter(), map(), collect(), etc.

4. Pipelining​

  • Multiple operations can be chained together (like filters and maps)

5. Internal Iteration​

  • Stream handles looping internally, unlike traditional for loops

Important Notes​

  • Streams belong to the package: java.util.stream
  • They do not store data; they only process it
  • They support lazy evaluation — operations are only performed when necessary