Java Stream Filter

Su Suriya Ravichandran Updated 18 Nov 2026
8 min read ·Lesson 173 of 306

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) or false (drop) for each element, usually written as a lambda or method reference.
  • filter is 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 a Stream<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:

OperationKeepsStops at the first failing element?
filter(p)Every element matching p, anywhere in the streamNo
takeWhile(p)Elements from the start, until the first one that fails pYes — the rest is dropped
dropWhile(p)Everything after the leading run of matching elementsDrops 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
OperationReturns true whenStops at
anyMatch(p)At least one element matchesThe first match
allMatch(p)Every element matchesThe first non-match
noneMatch(p)No element matchesThe first match
findFirst()— returns Optional of the first elementThe first element
findAny()— returns Optional of any elementAny element (faster in parallel)
  • filter(...).findFirst() is the stream version of "loop until you find it, then stop" and returns an Optional, which is empty when nothing matches (Optional Class lesson).
  • Empty streams: anyMatch is false, while allMatch and noneMatch are true — "all zero elements are in stock" is vacuously true. A validation such as items.stream().allMatch(Item::isValid) therefore passes for an empty list; check isEmpty() separately if an empty input should be rejected.
  • Prefer anyMatch(p) over filter(p).count() > 0 or filter(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: filter keeps only Upi objects, but the stream's type is still Stream<Payment>, so a map with a cast is needed to get a Stream<Upi>.
  • Upi.class::isInstance and Upi.class::cast do the same thing with method references on the Class object — a common idiom.
  • mapMulti (Java 16+) filters and converts in one step: for each element, the lambda can pass zero or more results to out.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:

  1. Each criterion is an Optional, empty when the user left the field blank. ifPresent adds a predicate only for fields that were filled in, so the number of rules matches what the user asked for.
  2. Lambdas capture the criterion values: max -> rules.add(c -> c.fee() <= max) creates a predicate that remembers the user's maximum fee.
  3. 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.)
  4. Combining: rules.stream().reduce(c -> true, Predicate::and) folds the list into one predicate: starting from "accept everything", each rule is and-ed on. With no rules, the result accepts every course — the "no filters" case. reduce is explained in the Stream Reduce lesson.
  5. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Stream Filter and get answers drawn from it.

Signed-in readers only.