Java Streams API

Learn about the Java Streams API. Process collections of data functionally using methods like filter, map, reduce, and sorted.

The Streams API (Java 8+) allows you to process sequences of elements (like collections) in a functional style.

Think of it like a Factory Assembly Line 🏭.

  • Raw materials (Data) come in.
  • Station 1: Filter out bad parts (filter).
  • Station 2: Paint them red (map).
  • Station 3: Sort them by size (sorted).
  • Station 4: Box them up (collect).

Creating a Stream

You can create a stream from a Collection (like ArrayList).

import java.util.ArrayList;
import java.util.stream.Stream;

ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

Stream<String> nameStream = names.stream();

Common Operations

1. Filter (Select specific items)

Keep only names starting with "A".

names.stream()
     .filter(s -> s.startsWith("A"))
     .forEach(System.out::println);
// Output: Alice

2. Map (Transform items)

Convert all names to Uppercase.

names.stream()
     .map(s -> s.toUpperCase())
     .forEach(System.out::println);
// Output: ALICE, BOB, CHARLIE

3. Sorted (Sort items)

Sort names alphabetically.

names.stream()
     .sorted()
     .forEach(System.out::println);

4. Collect (Convert back to List)

Usually, you want to save the result back into a List.

import java.util.List;
import java.util.stream.Collectors;

List<String> result = names.stream()
                           .filter(s -> s.length() > 3)
                           .collect(Collectors.toList());

Tip 💡: Streams don't change the original data structure. They create a new result. Your original names list remains untouched!

5. Reduce (Aggregate items)

Combine elements into a single result (e.g., sum, max).

int sum = numbers.stream()
                 .reduce(0, (a, b) -> a + b);

Parallel Streams

Parallel streams divide the task into multiple substreams that run on different threads (multi-core).

list.parallelStream()
    .forEach(System.out::println);

Warning ⚠️: Parallel streams can be faster for huge datasets but might be slower for small ones due to overhead. Also, be careful with thread safety!

Which Stream operation transforms elements?


Note : Java is a statically-typed language. It means that all variables must be declared before they can be used.

Challenge

Complete this chapter to unlock the next one.

Challenge

Task:

Use streams to filter numbers greater than 5 from a list [2, 8, 1, 9] and print them.