Nearby lessons

94 of 125

Java - Stream API

📌 What You Will Learn
  • Lambda expressions — the big change
  • Functional interfaces
  • Default and static methods in interfaces
  • The four workhorses: Predicate, Function, Consumer, Supplier
  • Method references (::)
  • The Stream API for processing collections
  • Optional — safe null handling
  • The new Date and Time API

Stream API is a core concept of the Java language. This lesson explains The Stream API — Processing Collections with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

The Stream API — Processing Collections

A Stream is a flow of elements we can process with chain-like steps: filter → sort → map → collect. The data source stays unchanged; the stream works on a copy-like flow.

In simple words: A stream pipeline never changes the original collection. filter, map and sorted work on a flow of elements, and only collect(...) builds a new result list at the end.

The pipeline is easy to read like English: take the numbers, keep only those above 10, double each, sort them, and collect.

Important Stream Operations

OperationWhat it does
filter(predicate)Keep only matching elements
map(function)Convert every element
sorted()Sort the stream
distinct()Remove duplicates
limit(n)Take only the first n elements
count()How many elements are there
forEach(consumer)Do something with each element
collect(...)Turn the stream back into a list/set/map
reduce(...)Combine all elements into one (like sum)
Example01
JCode Cell
1import java.util.*;
2import java.util.stream.*;
3 
4class StreamDemo {
5 public static void main(String[] args) {
6 List<Integer> numbers = List.of(5, 12, 3, 20, 8, 15);
7 
8 List<Integer> result = numbers.stream()
9 .filter(n -> n > 10) // keep numbers above 10
10 .map(n -> n * 2) // double them
11 .sorted() // sort
12 .collect(Collectors.toList()); // collect into a list
13 
14 System.out.println(result);
15 }
16}
Output
[16, 24, 30, 40]

The Stream API — Processing Collections

Example02
JCode Cell
1long count = numbers.stream().filter(n -> n % 2 == 0).count();
2System.out.println("Even numbers: " + count);
3 
4int sum = numbers.stream().reduce(0, (a, b) -> a + b);
5System.out.println("Sum: " + sum);
📝 Key Takeaways
  • Lambda = a function without a name; (params) -> logic.
  • Functional interface = one abstract method, so a lambda can implement it.
  • Interfaces now have default and static methods with bodies.
  • Predicate (test), Function (apply), Consumer (accept), Supplier (get) are the four core functional interfaces.
  • Method references (::) are shorthand for lambdas.
  • Streams process collections with filter/map/sorted/collect pipelines.
  • Optional prevents NullPointerException with orElse/isPresent.
  • java.time (LocalDate, LocalDateTime) replaces the old Date/Calendar cleanly.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1