Skip to main content

Lesson 3 of 8

Stream API - Creating & Intermediate Operations

The Stream API (Java 8+) enables declarative, pipeline-based data processing. A stream pipeline has: a source, zero or more intermediate operations (lazy), and a terminal operation (triggers execution). Streams do not store data - they process elements on demand.

18 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Stream Sources & Intermediate Operations

Stream Sources & Intermediate Operations
import java.util.*;
import java.util.stream.*;
import java.nio.file.*;

public class StreamIntermediate {
    public static void main(String[] args) throws Exception {
        // ── Creating Streams ─────────────────────────────────────
        Stream<String> fromList    = List.of("a","b","c").stream();
        Stream<String> fromArray   = Arrays.stream(new String[]{"x","y","z"});
        Stream<String> generated   = Stream.generate(() -> "repeat").limit(5);
        Stream<Integer> iterated   = Stream.iterate(0, n -> n + 2).limit(6); // 0,2,4,6,8,10
        Stream<String> ofStream    = Stream.of("A", "B", "C");
        Stream<String> lines       = Files.lines(Path.of("books.txt")); // lazy file read

        IntStream range   = IntStream.range(1, 6);    // 1,2,3,4,5
        IntStream rangeClosed = IntStream.rangeClosed(1, 5); // 1,2,3,4,5
        LongStream longs  = LongStream.of(100L, 200L, 300L);

        // ── Intermediate Operations (lazy - don't run until terminal) ──
        List<Book> books = getCatalog();

        books.stream()
             // filter(Predicate) - keep matching elements
             .filter(b -> b.isAvailable())
             .filter(b -> b.getPrice() < 50.0)

             // map(Function) - transform each element
             .map(b -> b.getTitle().toUpperCase())

             // distinct() - remove duplicates (uses equals/hashCode)
             .distinct()

             // sorted() - natural order | sorted(Comparator) - custom
             .sorted()

             // peek(Consumer) - side effect without consuming (great for debugging)
             .peek(t -> System.out.println("Processing: " + t))

             // limit(n) - take at most n elements
             .limit(10)

             // skip(n) - skip first n elements
             .skip(1)

             // terminal: forEach
             .forEach(System.out::println);

        // flatMap - flatten nested collections
        List<List<String>> nested = List.of(
            List.of("Java", "Python"),
            List.of("Go", "Rust"),
            List.of("TypeScript")
        );
        List<String> flat = nested.stream()
            .flatMap(Collection::stream)   // List<List<X>> → Stream<X>
            .collect(Collectors.toList()); // [Java, Python, Go, Rust, TypeScript]

        // mapToInt, mapToDouble - convert to primitive streams (avoids boxing)
        OptionalDouble avgPrice = books.stream()
            .mapToDouble(Book::getPrice)   // DoubleStream
            .average();

        // takeWhile / dropWhile (Java 9+) - ordered short-circuit
        IntStream.iterate(1, n -> n + 1)
                 .takeWhile(n -> n <= 5)   // [1, 2, 3, 4, 5] - stops at 6
                 .forEach(System.out::print);
    }

    static List<Book> getCatalog() { return new ArrayList<>(); /* placeholder */ }
}

Quick Quiz

Tip

Tip

Practice Stream API Creating Intermediate Operations in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Stream API - Creating & Intermediate Operations

Practice Task

Note

Practice Task - (1) Write a working example of Stream API Creating Intermediate Operations from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with Stream API Creating Intermediate Operations is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/8 done