Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Java Index

🌊 java.util.stream — Streams API — filter, map, reduce, collect (Java 8+)

The Streams API enables functional-style operations on collections. Streams are lazy — intermediate operations are not executed until a terminal operation is called. Combined with lambda expressions, streams replace most explicit for-loops in modern Java.

Import: import java.util.stream.*; | Docs: Oracle JavaDoc

📋 Classes, Methods & Constants

NameSignatureDescription
stream()default Stream<E> stream()Return sequential stream from Collection
Stream.ofstatic <T> Stream<T> of(T... values)Create stream from values
Stream.generatestatic <T> Stream<T> generate(Supplier<T> s)Create infinite stream from Supplier
Stream.iteratestatic <T> Stream<T> iterate(T seed, UnaryOperator<T> f)Create infinite iterated stream
filterStream<T> filter(Predicate<? super T> pred)Keep elements matching predicate
mapStream<R> map(Function<? super T,? extends R> f)Transform each element
mapToIntIntStream mapToInt(ToIntFunction<? super T> f)Map to IntStream for sum/avg/etc.
flatMapStream<R> flatMap(Function<? super T, Stream<R>> f)Map each element to stream and flatten
distinctStream<T> distinct()Remove duplicate elements
sortedStream<T> sorted()Sort using natural ordering
sorted(Comparator)Stream<T> sorted(Comparator<? super T> c)Sort with comparator
limitStream<T> limit(long maxSize)Truncate stream to maxSize elements
skipStream<T> skip(long n)Skip first n elements
peekStream<T> peek(Consumer<? super T> action)Perform action on each element (for debug)
forEachvoid forEach(Consumer<? super T> action)Terminal: perform action on each element
collectR collect(Collector<? super T,A,R> collector)Terminal: accumulate into collection
Collectors.toListstatic <T> Collector<T,?,List<T>> toList()Collect stream to List
Collectors.toSetstatic <T> Collector<T,?,Set<T>> toSet()Collect stream to Set
Collectors.joiningstatic Collector joining(CharSequence delim)Join strings with delimiter
Collectors.groupingBystatic Collector groupingBy(Function classifier)Group elements by classifier function
Collectors.countingstatic <T> Collector<T,?,Long> counting()Count elements in each group
countlong count()Terminal: return element count
sum / averageint sum() / OptionalDouble average()Terminal on IntStream/LongStream/DoubleStream
findFirstOptional<T> findFirst()Terminal: return first element
anyMatchboolean anyMatch(Predicate<? super T> pred)Terminal: true if any element matches
allMatchboolean allMatch(Predicate<? super T> pred)Terminal: true if all elements match
noneMatchboolean noneMatch(Predicate<? super T> pred)Terminal: true if no elements match
reduceOptional<T> reduce(BinaryOperator<T> acc)Terminal: combine elements with accumulator
min / maxOptional<T> min/max(Comparator<? super T> c)Terminal: find minimum/maximum element
toArrayObject[] toArray()Terminal: collect elements into array

💡 Example Program

Save as ClassName.java (matching the public class name), compile with javac ClassName.java, run with java ClassName.

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

public class StreamsDemo {
    record Student(String name, String major, int score) {}

    public static void main(String[] args) {
        List<Student> students = List.of(
            new Student("Alice",   "CS",   95),
            new Student("Bob",     "Math", 87),
            new Student("Carol",   "CS",   92),
            new Student("Dave",    "Math", 78),
            new Student("Eve",     "CS",   88),
            new Student("Frank",   "Math", 91)
        );

        // Filter + map + collect
        List<String> csTopStudents = students.stream()
            .filter(s -> s.major().equals("CS") && s.score() >= 90)
            .map(Student::name)
            .sorted()
            .collect(Collectors.toList());
        System.out.println("CS top students: " + csTopStudents);

        // groupingBy major → average score
        Map<String, Double> avgByMajor = students.stream()
            .collect(Collectors.groupingBy(Student::major,
                     Collectors.averagingInt(Student::score)));
        avgByMajor.forEach((major, avg) ->
            System.out.printf("  %-6s avg=%.2f%n", major, avg));

        // Statistics
        IntSummaryStatistics stats = students.stream()
            .mapToInt(Student::score)
            .summaryStatistics();
        System.out.printf("Min=%d Max=%d Avg=%.2f%n",
            stats.getMin(), stats.getMax(), stats.getAverage());

        // Joining
        String roster = students.stream()
            .sorted(Comparator.comparingInt(Student::score).reversed())
            .map(s -> s.name() + "(" + s.score() + ")")
            .collect(Collectors.joining(", "));
        System.out.println("Roster: " + roster);

        // FlatMap — all distinct characters across all names
        long uniqueChars = students.stream()
            .map(Student::name)
            .flatMap(n -> n.chars().mapToObj(c -> (char) c).map(String::valueOf))
            .distinct().count();
        System.out.println("Unique chars in all names: " + uniqueChars);
    }
}
// javac --enable-preview --release 21 StreamsDemo.java
// java  --enable-preview StreamsDemo

← java.io  |  🏠 Index  |  java.net →