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.
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.
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); }}
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()); }}