Stream API
The Stream API lets you process collections of data (like lists) in a clean, declarative style — describing what should happen (filter, transform, count) rather than manually writing loops to do it step-by-step.
1. What is the Stream API?
The Stream API lets you process collections of data (like lists) in a clean, declarative style — describing what should happen (filter, transform, count) rather than manually writing loops to do it step-by-step.
2. Why is it used?
It significantly reduces the amount of code needed for common data-processing tasks, like filtering a list of students by marks, or converting a list of names to uppercase, all in a few readable lines.
3. Real-Life Example
Think of a factory assembly line where raw material passes through several stages — cleaning, cutting, packaging — each stage doing one specific job before passing the result to the next. A Java Stream processes data through a similar chain of steps.
4. Syntax
javacollection.stream() .filter(condition) .map(transformation) .collect(Collectors.toList());
5. Example Program
javaimport java.util.*; import java.util.stream.*; public class StreamDemo { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> evenNumbers = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); System.out.println(evenNumbers); } }
Output:
[2, 4, 6]6. Key Points to Remember
- A stream doesn't store data itself — it simply processes data from an existing source, like a
List. - Stream operations don't modify the original collection; they produce a new result.
- Common operations include
filter(),map(),sorted(),collect(), andforEach().