Stream ofNullable Guards Null Entries

Feed possibly-null values through Stream.ofNullable and flatMap so nulls vanish at the source instead of triggering NPE mid-pipeline.

JavaData Integrity

Code

snippet
import java.util.List;
import java.util.stream.Stream;

public class NullableFeeder {

    record Ingredient(String name, Double grams) {}

    public static void main(String[] args) {
        // 一个含 null 的原始列表:ofNullable 单值入口
        String maybeNull = null;
        long count = Stream.ofNullable(maybeNull).count();
        System.out.println("single null produced " + count + " element(s)");

        List<Ingredient> pantry = List.of(
                new Ingredient("flour", 250.0),
                new Ingredient("sugar", null),
                new Ingredient("salt", 5.0),
                new Ingredient(null, null));

        // flatMap(Stream::ofNullable):null 元素贡献零项,管线中段不再抛 NPE
        List<String> named = pantry.stream()
                .map(Ingredient::name)
                .flatMap(Stream::ofNullable)
                .toList();
        System.out.println("named ingredients: " + named);

        // 对照 Stream.of(null):产生一个含 null 的流,后续 toLowerCase 才炸
        Stream<String> trap = Stream.of((String) null);
        System.out.println("Stream.of(null) count = " + trap.count());
    }
}

How it works

Structurally, expect the classes NullableFeeder and Ingredient and the function main and nothing else.

The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.

Points of care

  • The only prerequisite is the language toolchain itself.

Applying it

Signature: public static void main(String[] args)

The demo output is labeled (single null produced, named ingredients:, Stream.of(null) count =), so every printed line maps back to its originating operation.

Statements that matter

List<String> named = pantry.stream()
        .map(Ingredient::name)
        .flatMap(Stream::ofNullable)
        .toList();

Interactive Tools for This Topic

FAQ

What does Stream ofNullable Guards Null Entries print when run?
Invoke the file as-is — the `single null produced`, `named ingredients:`, `Stream.of(null) count =` prefixes identify which step printed each line.