Careeroza
Intermediate Operations
Common Intermediate Operations
| Operation | What it does |
|---|---|
filter(Predicate) | keep matching elements |
map(Function) | transform each element |
mapToInt / mapToObj | switch between object and primitive streams |
flatMap(Function) | one element → many, flattened |
distinct() | remove duplicates (uses equals) |
sorted(), sorted(Comparator) | sort |
limit(n), skip(n) | take first n / skip first n (pagination) |
takeWhile / dropWhile (Java 9) | take / drop while a condition holds |
peek(Consumer) | look at elements (debugging only) |
mapMulti (Java 16) | imperative alternative to flatMap |
Products Page Pipeline
Example
Page 2 of in-stock products (2 per page), sorted by price.
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Product> products = List.of(
new Product("Phone", 15999, 5), new Product("Cover", 299, 0),
new Product("Charger", 899, 12), new Product("Earbuds", 1999, 3),
new Product("Cable", 199, 40), new Product("Phone", 15999, 5));
int page = 2, size = 2;
List<String> pageItems = products.stream()
.distinct()
.filter(p -> p.stock() > 0)
.sorted(Comparator.comparingInt(Product::price))
.skip((long) (page - 1) * size)
.limit(size)
.map(p -> p.name() + " Rs" + p.price())
.toList();
System.out.println(pageItems);
List<Integer> temps = List.of(28, 30, 33, 36, 31, 29);
System.out.println("takeWhile < 35: " + temps.stream().takeWhile(t -> t < 35).toList());
System.out.println("dropWhile < 35: " + temps.stream().dropWhile(t -> t < 35).toList());
}
}
record Product(String name, int price, int stock) {}Output
[Earbuds Rs1999, Phone Rs15999] takeWhile < 35: [28, 30, 33] dropWhile < 35: [36, 31, 29]
Practice
Exercise: From List.of(5, 3, 5, 1, 3, 8) get the distinct numbers in descending order.
Show answer
List<Integer> r = List.of(5, 3, 5, 1, 3, 8).stream()
.distinct()
.sorted(Comparator.reverseOrder())
.toList();
System.out.println(r); // [8, 5, 3, 1]