Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Filtering and transformations in Java

Filtering and transformations in Java: Filtering keeps elements satisfying a Predicate, map transforms each element, and flatMap expands each result into zero or more values in Stream or Optional.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

filtering transformations

Filtering keeps elements satisfying a Predicate, map transforms each element, and flatMap expands each result into zero or more values in Stream or Optional.

Compose Stream.filter/map/flatMap for collections and Optional.filter/map/flatMap for optional values, avoiding nested Optional<Optional> and Stream<Stream>.

Stream functions should be stateless and non-interfering; map does not run without a terminal operation, and side effects may be elided or reordered in parallel.

Optional.map turns a null result into empty, Optional.flatMap must not return null, while Stream.flatMap treats a null substream as empty and closes consumed substreams.

The Stream trims text, drops the empty element, splits and uppercases to [A, B, C], while the Optional chain yields length 4.

Examples

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        var result = List.of(" a,b ", "", " c ").stream()
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .flatMap(s -> Arrays.stream(s.split(",")))
                .map(String::toUpperCase)
                .toList();
        int length = Optional.of("  java ")
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .map(String::length)
                .orElse(0);
        System.out.println(result);
        System.out.println(length);
    }
}

Result

[A, B, C]
4

The Stream trims text, drops the empty element, splits and uppercases to [A, B, C], while the Optional chain yields length 4.

Sources