TExcelTAD
Home › Java › Java Streams API

Java Streams API

The Streams API (java.util.stream) lets you process collections in a declarative way: you describe what you want — "the names of all active customers, sorted, in upper case" — and the library takes care of the looping. A stream pipeline reads almost like a sentence.

Anatomy of a stream pipeline

  1. A source creates the stream: list.stream(), Stream.of(...), Arrays.stream(array), IntStream.range(...).
  2. Zero or more intermediate operations transform it: filter, map, sorted, distinct, limit...
  3. One terminal operation produces the result: toList, count, sum, forEach, collect...
java · try it yourself
import java.util.List;

class Main {
    public static void main(String[] args) {
        List<String> names = List.of("anna", "Bob", "chris", "Dana", "eve", "Frank");

        List<String> result = names.stream()
                .filter(n -> n.length() > 3)          // keep long names
                .map(String::toUpperCase)             // transform each
                .sorted()                             // natural order
                .toList();                            // terminal: collect to a list

        System.out.println(result);
        System.out.println(names);                    // the source is unchanged
    }
}
[ANNA, CHRIS, DANA, FRANK]
[anna, Bob, chris, Dana, eve, Frank]

Streams don't modify their source, and a stream can be consumed only once. Intermediate operations are lazy: nothing happens until a terminal operation runs.

Common operations

Operation Kind Does
filter(predicate) intermediate keeps matching elements
map(function) intermediate transforms each element
sorted() / sorted(cmp) intermediate sorts
distinct() intermediate removes duplicates
limit(n) / skip(n) intermediate takes / skips the first n
toList() terminal collects into an unmodifiable list
count() terminal number of elements
forEach(action) terminal runs an action for each
anyMatch / allMatch / noneMatch terminal boolean tests
findFirst() / min / max terminal return an Optional
reduce(identity, op) terminal combines all elements into one
collect(collector) terminal flexible collection (maps, groups, strings)

Numbers: IntStream and friends

Primitive streams (IntStream, LongStream, DoubleStream) avoid boxing and add numeric operations like sum, average and summaryStatistics:

java · try it yourself
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.IntStream;

class Main {
    public static void main(String[] args) {
        System.out.println(IntStream.rangeClosed(1, 10).sum());
        System.out.println(IntStream.range(0, 5).map(i -> i * i).boxed().toList());

        List<Integer> scores = List.of(72, 95, 58, 88, 64);
        double avg = scores.stream().mapToInt(Integer::intValue).average().orElse(0);
        System.out.println("Average: " + avg);

        IntSummaryStatistics stats = scores.stream().mapToInt(s -> s).summaryStatistics();
        System.out.println("min=" + stats.getMin() + " max=" + stats.getMax() + " count=" + stats.getCount());

        int product = IntStream.rangeClosed(1, 5).reduce(1, (a, b) -> a * b);
        System.out.println("5! = " + product);
        System.out.println(scores.stream().anyMatch(s -> s < 60));
    }
}
55
[0, 1, 4, 9, 16]
Average: 75.4
min=58 max=95 count=5
5! = 120
true

Working with objects

Streams shine on lists of records or objects:

java · try it yourself
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

record Order(String customer, String product, int qty, double price) {
    double total() { return qty * price; }
}

class Main {
    public static void main(String[] args) {
        List<Order> orders = List.of(
            new Order("Ada", "keyboard", 1, 49.0),
            new Order("Ben", "cable", 3, 5.5),
            new Order("Ada", "monitor", 2, 189.0),
            new Order("Cleo", "mouse", 1, 19.9),
            new Order("Ben", "laptop", 1, 999.0)
        );

        double revenue = orders.stream().mapToDouble(Order::total).sum();
        System.out.printf("Revenue: %.2f%n", revenue);

        String bigOrders = orders.stream()
                .filter(o -> o.total() > 100)
                .sorted(Comparator.comparingDouble(Order::total).reversed())
                .map(o -> o.customer() + ":" + o.product())
                .collect(Collectors.joining(", ", "[", "]"));
        System.out.println("Big orders: " + bigOrders);

        List<String> customers = orders.stream().map(Order::customer).distinct().sorted().toList();
        System.out.println("Customers: " + customers);
    }
}
Revenue: 1462.40
Big orders: [Ben:laptop, Ada:monitor]
Customers: [Ada, Ben, Cleo]

Grouping and collecting to maps

Collectors.groupingBy is like SQL's GROUP BY. Passing TreeMap::new keeps the keys sorted so the output order is predictable:

java · try it yourself
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

class Main {
    public static void main(String[] args) {
        List<String> words = List.of("apple", "avocado", "banana", "blueberry", "cherry", "apricot");

        Map<Character, List<String>> byLetter = words.stream()
                .collect(Collectors.groupingBy(w -> w.charAt(0), TreeMap::new, Collectors.toList()));
        System.out.println(byLetter);

        Map<Character, Long> counts = words.stream()
                .collect(Collectors.groupingBy(w -> w.charAt(0), TreeMap::new, Collectors.counting()));
        System.out.println(counts);

        Map<Boolean, List<String>> longOrShort = words.stream()
                .collect(Collectors.partitioningBy(w -> w.length() > 6));
        System.out.println(longOrShort);

        Map<String, Integer> lengths = words.stream()
                .collect(Collectors.toMap(w -> w, String::length, (a, b) -> a, TreeMap::new));
        System.out.println(lengths);
    }
}
{a=[apple, avocado, apricot], b=[banana, blueberry], c=[cherry]}
{a=3, b=2, c=1}
{false=[apple, banana, cherry], true=[avocado, blueberry, apricot]}
{apple=5, apricot=7, avocado=7, banana=6, blueberry=9, cherry=6}

Tip: Streams are not always better than loops. Use them when the pipeline reads clearly; fall back to a loop when you need complex control flow, early exits with side effects, or checked exceptions.

Test yourself

Which of these is a terminal operation?

  1. filter
  2. map
  3. sorted
  4. count

What does Stream.of(1, 2, 3, 4).filter(n -> n % 2 == 0).map(n -> n * 10).toList() return?

  1. [10, 30]
  2. [20, 40]
  3. [2, 4]
  4. [10, 20, 30, 40]

What happens to the source list when you run a stream pipeline on it?

  1. It is sorted in place
  2. It is emptied
  3. It is unchanged
  4. It is replaced by the result