Java Stream Filter
The filter Operation
filter keeps the elements that satisfy a condition and drops the rest:
Stream<T> filter(Predicate<? super T> predicate)
- The predicate is a function that returns
true(keep) orfalse(drop) for each element, usually written as a lambda or method reference. filteris an intermediate operation: it returns a new stream and does nothing until a terminal operation runs.- It's stateless: each element is judged on its own, so it works on infinite streams and in parallel without extra cost.
- The element type doesn't change — a
Stream<Order>stays aStream<Order>, possibly with fewer elements. - The source collection isn't modified. To remove elements from a collection itself, use
collection.removeIf(predicate).
Besides filter, several other operations select elements: distinct, limit, skip, takeWhile, dropWhile, and the matching and finding operations. This lesson covers all of them.
Filtering, Cleaning and Selecting
import java.util.*;
import java.util.stream.*;
public class F1 {
public static void main(String[] args) {
List<String> emails = Arrays.asList("asha@gocourse.in", null, " ", "ravi@gocourse.in", "invalid", "ASHA@gocourse.in");
List<String> valid = emails.stream()
.filter(Objects::nonNull)
.filter(e -> !e.isBlank())
.filter(e -> e.contains("@"))
.map(String::toLowerCase)
.distinct()
.toList();
System.out.println(valid);
List<Integer> nums = List.of(5, 12, 7, 20, 3, 15, 8);
System.out.println("skip/limit page 2: " + nums.stream().skip(3).limit(3).toList());
System.out.println("filter < 10: " + nums.stream().filter(n -> n < 10).toList());
System.out.println("takeWhile < 10: " + nums.stream().takeWhile(n -> n < 10).toList());
System.out.println("dropWhile < 10: " + nums.stream().dropWhile(n -> n < 10).toList());
List<Integer> sorted = nums.stream().sorted().toList();
System.out.println("sorted takeWhile: " + sorted.stream().takeWhile(n -> n < 10).toList());
}
}
Output:
[asha@gocourse.in, ravi@gocourse.in]
skip/limit page 2: [20, 3, 15]
filter < 10: [5, 7, 3, 8]
takeWhile < 10: [5]
dropWhile < 10: [12, 7, 20, 3, 15, 8]
sorted takeWhile: [3, 5, 7, 8]
Cleaning input with several filters
The email pipeline removes null values first (Objects::nonNull is a ready-made predicate), then blank strings, then values without @. Order matters: the null check must come first, otherwise e.isBlank() would throw NullPointerException. Several small filters, each with one clear rule, are easier to read and change than one combined condition; performance is the same, because the stream fuses them into a single pass.
distinct
distinct() removes duplicates using equals and hashCode. Because the emails are lowercased first, ASHA@gocourse.in becomes a duplicate of asha@gocourse.in and is dropped; the first occurrence is kept. distinct is stateful — it remembers every element it has seen — so on very large streams it uses memory proportional to the number of distinct elements. For your own classes, it only works correctly if equals and hashCode are implemented (records do this automatically).
skip and limit
skip(n) drops the first n elements and limit(n) keeps at most n. Together they select a page: skip((page - 1) * size).limit(size) gives page 2 of size 3 as elements 4–6. On an unsorted stream this is only meaningful if the order is stable — for real paging, sort first, or let the database page the data.
takeWhile and dropWhile (Java 9+)
These look like filter but behave very differently:
| Operation | Keeps | Stops at the first failing element? |
|---|---|---|
filter(p) | Every element matching p, anywhere in the stream | No |
takeWhile(p) | Elements from the start, until the first one that fails p | Yes — the rest is dropped |
dropWhile(p) | Everything after the leading run of matching elements | Drops the leading run only |
On the unsorted list, takeWhile(n < 10) returns only [5], because 12 fails and everything after it is ignored — even 7 and 3. On the sorted list, it returns all values below 10 and stops as soon as it reaches 12, without examining the rest. takeWhile is therefore ideal for ordered data — sorted lists, time-ordered logs, generated sequences — where it can stop early, and wrong for unordered data, where you want filter.
Matching and Finding
These terminal operations answer yes/no questions or return a single element, and they short-circuit — they stop as soon as the answer is known:
import java.util.*;
public class Match {
record Item(String name, int qty, double price) { }
public static void main(String[] args) {
List<Item> cart = List.of(new Item("pen", 2, 25), new Item("bag", 1, 1899), new Item("ink", 0, 80));
System.out.println("any free? " + cart.stream().anyMatch(i -> i.price() == 0));
System.out.println("all in stock? " + cart.stream().allMatch(i -> i.qty() > 0));
System.out.println("none over 5000? " + cart.stream().noneMatch(i -> i.price() > 5000));
System.out.println("first expensive: " + cart.stream().filter(i -> i.price() > 1000).findFirst().map(Item::name).orElse("none"));
List<Item> empty = List.of();
System.out.println("empty: any=" + empty.stream().anyMatch(i -> true)
+ " all=" + empty.stream().allMatch(i -> false)
+ " none=" + empty.stream().noneMatch(i -> true));
}
}
Output:
any free? false
all in stock? false
none over 5000? true
first expensive: bag
empty: any=false all=true none=true
| Operation | Returns true when | Stops at |
|---|---|---|
anyMatch(p) | At least one element matches | The first match |
allMatch(p) | Every element matches | The first non-match |
noneMatch(p) | No element matches | The first match |
findFirst() | — returns Optional of the first element | The first element |
findAny() | — returns Optional of any element | Any element (faster in parallel) |
filter(...).findFirst()is the stream version of "loop until you find it, then stop" and returns anOptional, which is empty when nothing matches (Optional Class lesson).- Empty streams:
anyMatchisfalse, whileallMatchandnoneMatcharetrue— "all zero elements are in stock" is vacuously true. A validation such asitems.stream().allMatch(Item::isValid)therefore passes for an empty list; checkisEmpty()separately if an empty input should be rejected. - Prefer
anyMatch(p)overfilter(p).count() > 0orfilter(p).findFirst().isPresent(): it says what you mean and stops at the first match.
Filtering by Type
A stream of a general type (an interface or parent class) often needs to be narrowed to one subtype:
import java.util.*;
public class Types {
sealed interface Payment permits Card, Upi, Cash { double amount(); }
record Card(String last4, double amount) implements Payment { }
record Upi(String vpa, double amount) implements Payment { }
record Cash(double amount) implements Payment { }
public static void main(String[] args) {
List<Payment> payments = List.of(new Card("4242", 4999), new Upi("asha@okbank", 2999),
new Cash(500), new Upi("ravi@okbank", 1200));
List<String> upiIds = payments.stream()
.filter(p -> p instanceof Upi)
.map(p -> (Upi) p)
.map(Upi::vpa)
.toList();
System.out.println(upiIds);
double upiTotal = payments.stream()
.filter(Upi.class::isInstance)
.map(Upi.class::cast)
.mapToDouble(Upi::amount)
.sum();
System.out.println(upiTotal);
List<String> cards = payments.stream()
.<String>mapMulti((p, out) -> { if (p instanceof Card c) out.accept("**** " + c.last4()); })
.toList();
System.out.println(cards);
}
}
Output:
[asha@okbank, ravi@okbank]
4199.0
[**** 4242]
filter+ cast:filterkeeps onlyUpiobjects, but the stream's type is stillStream<Payment>, so amapwith a cast is needed to get aStream<Upi>.Upi.class::isInstanceandUpi.class::castdo the same thing with method references on theClassobject — a common idiom.mapMulti(Java 16+) filters and converts in one step: for each element, the lambda can pass zero or more results toout.accept(...). Combined with pattern matching (p instanceof Card c), it avoids the separate cast. The explicit<String>tells the compiler the result type.
Practical Example: A Search with Optional Criteria
A course search form has several optional fields — keyword, level, maximum fee, minimum rating, "certificate only". Any combination may be filled in. Instead of writing a filter for each combination, each filled-in field contributes one predicate, and the predicates are combined into a single filter.
import java.util.*;
import java.util.function.*;
public class Search {
record Course(String title, String level, String language, double fee, double rating, boolean certificate) { }
record Criteria(Optional<String> keyword, Optional<String> level, Optional<Double> maxFee,
Optional<Double> minRating, boolean certificateOnly) {
Predicate<Course> toPredicate() {
List<Predicate<Course>> rules = new ArrayList<>();
keyword.map(String::toLowerCase).ifPresent(k -> rules.add(c -> c.title().toLowerCase().contains(k)));
level.ifPresent(l -> rules.add(c -> c.level().equalsIgnoreCase(l)));
maxFee.ifPresent(max -> rules.add(c -> c.fee() <= max));
minRating.ifPresent(min -> rules.add(c -> c.rating() >= min));
if (certificateOnly) rules.add(Course::certificate);
return rules.stream().reduce(c -> true, Predicate::and);
}
}
static final List<Course> CATALOG = List.of(
new Course("Java Programming", "beginner", "Tamil", 4999, 4.8, true),
new Course("Advanced Java Streams", "advanced", "English", 6999, 4.6, true),
new Course("Python Basics", "beginner", "English", 2999, 4.5, false),
new Course("Django Web Development", "intermediate", "Tamil", 5999, 4.7, true),
new Course("Docker Essentials", "intermediate", "English", 3999, 4.2, false),
new Course("JavaScript for Beginners", "beginner", "Tamil", 3499, 4.4, true));
static void run(String label, Criteria c) {
List<String> hits = CATALOG.stream().filter(c.toPredicate()).map(Course::title).toList();
System.out.println(label + " -> " + hits);
}
public static void main(String[] args) {
run("no filters ", new Criteria(Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), false));
run("keyword 'java' ", new Criteria(Optional.of("java"), Optional.empty(), Optional.empty(), Optional.empty(), false));
run("beginner, <= 4000 ", new Criteria(Optional.empty(), Optional.of("Beginner"), Optional.of(4000.0), Optional.empty(), false));
run("rating >= 4.6, cert ", new Criteria(Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(4.6), true));
run("'java' + cert + <=5000 ", new Criteria(Optional.of("JAVA"), Optional.empty(), Optional.of(5000.0), Optional.empty(), true));
}
}
Output:
no filters -> [Java Programming, Advanced Java Streams, Python Basics, Django Web Development, Docker Essentials, JavaScript for Beginners]
keyword 'java' -> [Java Programming, Advanced Java Streams, JavaScript for Beginners]
beginner, <= 4000 -> [Python Basics, JavaScript for Beginners]
rating >= 4.6, cert -> [Java Programming, Advanced Java Streams, Django Web Development]
'java' + cert + <=5000 -> [Java Programming, JavaScript for Beginners]
How it works:
- Each criterion is an
Optional, empty when the user left the field blank.ifPresentadds a predicate only for fields that were filled in, so the number of rules matches what the user asked for. - Lambdas capture the criterion values:
max -> rules.add(c -> c.fee() <= max)creates a predicate that remembers the user's maximum fee. - The keyword match is case-insensitive — the keyword is lowercased once, outside the predicate, and each title is lowercased when compared. (
"java"also matches "JavaScript", as a simple substring search does.) - Combining:
rules.stream().reduce(c -> true, Predicate::and)folds the list into one predicate: starting from "accept everything", each rule isand-ed on. With no rules, the result accepts every course — the "no filters" case.reduceis explained in the Stream Reduce lesson. - One filter call applies the combined predicate to the catalogue. Adding a new search field means adding one line to
toPredicate.
Database-backed applications apply the same idea to queries — Spring Data's Specification and JPA's Criteria API combine optional conditions in exactly this way, but turn them into SQL so the database does the filtering.