AI Hints
Home›Java Tutorial›Streams, filter, map and collect, More Stream Operations
Java · Lesson 103 of 120

Streams

Process data step by step.

⏱ 2 min read▶ Video at 2:11:44🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

A stream is a pipeline for data. Values flow through a series of steps, like filter, and map, and come out as a result. It's a clear way to say what you want, not how to loop.

  • A data pipeline
  • Steps like filter and map
  • Say what, not how

A stream pipeline

First you get a stream, from a list or an array. Then you add steps, that each change or filter the values. Finally, a last step, like sum, or collect, produces the result. Nothing runs until that last step.

  1. List
  2. stream()
  3. filter
  4. map
  5. sum / collect

A loop, and a stream

Both do the same job. Take the numbers bigger than five, double them, and add them up. The loop says how, step by step. The stream reads like a sentence. Filter keeps the big numbers. Map to int doubles each one. And sum adds them. Run it. Both give one hundred and six.

Main.javajava
import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> nums = List.of(4, 9, 15, 2, 21, 8);
        int bigTotal = 0;
        for (int n : nums) {
            if (n > 5) bigTotal += n * 2;
        }
        System.out.println("Loop:   " + bigTotal);
        int streamTotal = nums.stream()
                              .filter(n -> n > 5)
                              .mapToInt(n -> n * 2)
                              .sum();
        System.out.println("Stream: " + streamTotal);
    }
}
Output
Loop:   106
Stream: 106

Where streams come from

Any list has a stream method. Stream dot of makes one from values. Int stream dot range closed makes a run of numbers. And Arrays dot stream works on arrays. Run it. Three items. One, two, three, sorted. The numbers one to five add up to fifteen. And the biggest is nine.

Main.javajava
import java.util.*;
import java.util.stream.*;
public class Main {
    public static void main(String[] args) {
        System.out.println(List.of("a", "b", "c").stream().count());
        System.out.println(Stream.of(3, 1, 2).sorted().toList());
        System.out.println(IntStream.rangeClosed(1, 5).sum());
        System.out.println(Arrays.stream(new int[]{7, 8, 9}).max().getAsInt());
    }
}
Output
3
[1, 2, 3]
15
9

Summary

A stream sends values through a pipeline of steps, and ends with a final step that gives a result. Next, the three most useful steps.

Key takeaways
  • source.stream()
  • Steps…
  • Final step
Next up: filter, map and collect — the big three