Skip to lesson

Keep elements with filter

filter keeps only the elements that pass a test and drops the rest. You give it a Predicate, a function that takes one element and returns true (keep it) or false (drop it).

Why filter exists

filter keeps only the elements for which a Predicate returns true and passes them on in the same order.

Most data work starts by throwing things away. A results page shows only students who passed. A bank statement shows only debits. A support team reads only failed payments.

Example 1 · Loop versus filter: keep students who passed

PassFilterDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class PassFilterDemo {    public static void main(String[] args) {        List<Integer> marks = List.of(72, 35, 88, 40, 19, 64);
        // old way: empty list, loop, if, add        List<Integer> passedLoop = new ArrayList<>();        for (int m : marks) {            if (m >= 40) {                passedLoop.add(m);            }        }        System.out.println("Loop:   " + passedLoop);
        // stream way: only the test is written        List<Integer> passed = marks.stream()                .filter(m -> m >= 40)                .toList();        System.out.println("Stream: " + passed);        System.out.println("Source: " + marks);    }}
Output
Loop:   [72, 88, 40, 64]
Stream: [72, 88, 40, 64]
Source: [72, 35, 88, 40, 19, 64]

What this code does

  • Both versions keep the marks of 40 and above, in the original order. In the stream version you write only the test m -> m >= 40.
  • The last line shows that filter never changes the source list. It builds a new result.
  • Why: the cost is the same, one pass over the marks. The stream states the rule m >= 40 and hides the list building.

With a loop you write the same frame every time: make an empty list, loop, check with if, add the ones that pass. The check is the only part that changes. filter keeps the frame inside the stream and asks you for that check alone: marks.stream().filter(m -> m >= 40). filter is an intermediate operation: it returns a new stream and does nothing until a terminal operation such as toList() or count() runs. The source list is never changed.

The predicate answers one question: should this element stay? true means keep, false means drop.

How one element moves through filter

Take the marks 72, 35, 88, 40. The pipeline is marks.stream().filter(m -> m >= 40).toList().

FilterMarks.javaJava
import java.util.*;
public class FilterMarks {    public static void main(String[] args) {        List<Integer> marks = List.of(72, 35, 88, 40);        List<Integer> passed = marks.stream().filter(m -> m >= 40).toList();        System.out.println(passed);        System.out.println(marks);    }}
Output
[72, 88, 40]
[72, 35, 88, 40]
  1. 72 arrives. 72 >= 40 is true, so it goes on to toList().
  2. 35 arrives. 35 >= 40 is false, so it is dropped and nothing later sees it.
  3. 88 arrives. The test is true, so it goes on.
  4. 40 arrives. 40 >= 40 is true (watch the >=), so it goes on. The result is [72, 88, 40], in the original order.

Trace the code

Watch filter decide

import java.util.List;
public class FilterTrace {
public static void main(String[] args) {
List<Integer> marks = List.of(72, 35, 88);
marks.stream()
.filter(m -> {
System.out.println("test " + m);
return m >= 40;
})
.forEach(m -> System.out.println("keep " + m));
}
}

Variables

marks
[72, 35, 88]

Output

(nothing printed yet)

Line 5marks holds three values. Building the pipeline does not run any step yet.

Step 1 of 9

Several filters or one combined condition

You can chain filters: .filter(s -> s.marks() >= 40).filter(s -> s.city().equals("Pune")). An element must pass every filter to reach the end, so two filters act like &&. The result is the same as one .filter(s -> s.marks() >= 40 && s.city().equals("Pune")).

Example 2 · Records in a filter, and two filters versus one

CombinedFilterDemo.javaJava
import java.util.List;
record Student(String name, String city, int marks) {}
public class CombinedFilterDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", "Pune", 78),                new Student("Ravi", "Delhi", 91),                new Student("Meena", "Pune", 34),                new Student("Kiran", "Pune", 66),                new Student("Farhan", "Delhi", 39));
        System.out.println("Two filters:");        students.stream()                .filter(s -> s.marks() >= 40)                .filter(s -> s.city().equals("Pune"))                .forEach(s -> System.out.println("  " + s.name() + " " + s.marks()));
        System.out.println("One combined filter:");        students.stream()                .filter(s -> s.marks() >= 40 && s.city().equals("Pune"))                .forEach(s -> System.out.println("  " + s.name() + " " + s.marks()));
        long passedEither = students.stream()                .filter(s -> s.marks() >= 90 || s.city().equals("Delhi"))                .count();        System.out.println("Toppers or Delhi: " + passedEither);    }}
Output
Two filters:
  Asha 78
  Kiran 66
One combined filter:
  Asha 78
  Kiran 66
Toppers or Delhi: 2

What this code does

  • An element must pass every filter in the chain, so two filters give the same result as one filter with &&.
  • For "either" rules you need || inside one filter. Ravi and Farhan are from Delhi, and Ravi is also a topper, so the count is 2.

Pick the form that reads best. Separate filters suit separate business rules, because each line says one thing. One combined filter suits a short condition that belongs together, such as a range m >= 40 && m <= 59. Speed is almost the same either way, because the stream still walks the data once. There is no chained form of ||. For "either this or that" you need one filter with ||, or a combined predicate with or.

Named predicates and Predicate.not

A long lambda inside filter hides the rule. Give the rule a name instead: Predicate<Student> passed = s -> s.marks() >= 40;. Now the pipeline reads like a sentence: .filter(passed). The same predicate can be reused in many pipelines and tested on its own.

Example 3 · Named predicates, negate and Predicate.not

NamedPredicateDemo.javaJava
import java.util.List;import java.util.function.Predicate;
record Student(String name, int marks, int feesDue) {}
public class NamedPredicateDemo {    public static void main(String[] args) {        List<Student> students = List.of(                new Student("Asha", 78, 0),                new Student("Ravi", 35, 1500),                new Student("Meena", 82, 2500),                new Student("Kiran", 29, 0));
        Predicate<Student> passed = s -> s.marks() >= 40;        Predicate<Student> hasDues = s -> s.feesDue() > 0;
        System.out.println("Passed, no dues:");        students.stream()                .filter(passed.and(hasDues.negate()))                .forEach(s -> System.out.println("  " + s.name()));
        System.out.println("Failed or has dues:");        students.stream()                .filter(passed.negate().or(hasDues))                .forEach(s -> System.out.println("  " + s.name()));
        List<String> remarks = List.of("Good work", "  ", "", "Revise loops");        List<String> real = remarks.stream()                .filter(Predicate.not(String::isBlank))                .toList();        System.out.println("Remarks kept: " + real);    }}
Output
Passed, no dues:
  Asha
Failed or has dues:
  Ravi
  Meena
  Kiran
Remarks kept: [Good work, Revise loops]

What this code does

  • passed and hasDues are written once and reused. and, or and negate build new predicates from them, so the pipeline reads like the rule itself.
  • Predicate.not(String::isBlank) flips a method reference. isBlank (Java 11) is true for empty text and text with only spaces, so both are dropped.

Example 4 · Real-world use: keep only failed UPI transactions

FailedUpiDemo.javaJava
import java.util.List;import java.util.function.Predicate;
record Txn(String id, String status, int amount) {}
public class FailedUpiDemo {    public static void main(String[] args) {        List<String> log = List.of(                "TXN101,SUCCESS,250",                "TXN102,FAILED,1200",                "TXN103,SUCCESS,80",                "TXN104,FAILED,450",                "TXN105,PENDING,999",                "TXN106,FAILED,60");
        Predicate<Txn> isFailed = t -> t.status().equals("FAILED");        Predicate<Txn> isLarge = t -> t.amount() >= 100;
        int total = 0;        for (String line : log) {            String[] p = line.split(",");            Txn t = new Txn(p[0], p[1], Integer.parseInt(p[2]));            if (isFailed.and(isLarge).test(t)) {                System.out.println("Refund check: " + t.id() + " Rs " + t.amount());                total += t.amount();            }        }        System.out.println("Amount to check: Rs " + total);
        long failedCount = log.stream()                .filter(line -> line.contains(",FAILED,"))                .count();        System.out.println("Failed lines: " + failedCount);    }}
Output
Refund check: TXN102 Rs 1200
Refund check: TXN104 Rs 450
Amount to check: Rs 1650
Failed lines: 3

What this code does

  • A predicate is an ordinary object, so isFailed.and(isLarge).test(t) works even inside a loop. The same named rule can move into a stream later without changes.
  • The last pipeline filters the raw log lines directly. contains(",FAILED,") with the commas avoids matching a word such as FAILED_RETRY in another column.

Named predicates combine with and, or and negate: passed.and(fromPune), passed.negate(). To flip a method reference, use the static Predicate.not (Java 11): .filter(Predicate.not(String::isBlank)) keeps lines that are not blank. You cannot write !String::isBlank.

Name a predicate after the question it answers: isFailed, hasDues, isWeekend. Then .filter(isFailed) needs no comment.

Trap: null elements inside the list

Lists from files, forms or old code sometimes hold null. A predicate such as s -> s.startsWith("TXN") calls a method on the element, and calling a method on null throws a NullPointerException. The whole pipeline stops at that element.

Example 5 · Trap: a null element crashes the filter

NullFilterDemo.javaJava
import java.util.Arrays;import java.util.List;import java.util.Objects;
public class NullFilterDemo {    public static void main(String[] args) {        // Arrays.asList allows null; List.of does not        List<String> ids = Arrays.asList("TXN101", null, "REF202", "TXN303", null);
        try {            long count = ids.stream()                    .filter(id -> id.startsWith("TXN"))                    .count();            System.out.println("Count: " + count);        } catch (NullPointerException e) {            System.out.println("Crashed with NullPointerException");        }
        List<String> txnIds = ids.stream()                .filter(Objects::nonNull)                .filter(id -> id.startsWith("TXN"))                .toList();        System.out.println("Safe: " + txnIds);    }}
Output
Crashed with NullPointerException
Safe: [TXN101, TXN303]

What this code does

  • The second element is null, and null.startsWith(...) throws a NullPointerException. The program never reaches the count.
  • .filter(Objects::nonNull) as the first step drops every null, so the next filter only ever sees real Strings.

Put a null check first: .filter(Objects::nonNull) drops every null before any other step runs. If only one field can be null, test it inside the lambda with s.status() != null && ..., keeping the null check on the left so && stops before the method call. A safer comparison is "FAILED".equals(s.status()), which returns false for null instead of throwing.

Next step

Check your understanding

12 quick questions