Java Streams API

Introduction

Java Streams API is a modern way to work with collections of data. It helps you do operations like filtering, sorting, and mapping in a clean and easy way.

Streams were added in Java 8. They let you write short and clear code.

What is a Stream?

A stream is a sequence of data. It does not store data. It only processes data from a source like a list, array, or set.

Think of it like a water pipe. The data flows through the pipe, and you can change it along the way.

Everyday Example

Imagine you have a basket of apples. You want to pick only red apples, clean them, and put them in a box.

This is similar to how a stream works:

Basic Stream Operations

Example in Code

import java.util.*;
import java.util.stream.*;

public class StreamExample {
    public static void main(String[] args) {
        List names = Arrays.asList("Alice", "Bob", "Charlie", "Anna");

        List result = names.stream()
            .filter(name -> name.startsWith("A"))
            .map(String::toUpperCase)
            .collect(Collectors.toList());

        System.out.println(result); // [ALICE, ANNA]
    }
}
  

Types of Streams

Intermediate vs Terminal Operations

Lazy Evaluation

Streams only run when needed. If you write a stream but do not call a terminal operation, nothing happens.

Parallel Streams

Java can run streams in parallel using parallelStream(). This makes them faster for big data.

List numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.parallelStream().forEach(System.out::println);
  

Conclusion

Streams are powerful. They help you write clean and short code. You can filter, map, and collect data easily. Try them in your next Java project!