Java Stream filter() Method

The filter() method in Java, part of the java.util.stream.Stream interface, is used to produce a new Stream that contains only those elements of the original stream that match a given predicate. This method is useful for removing unwanted elements from a stream based on a specified condition.

Table of Contents

  1. Introduction
  2. filter() Method Syntax
  3. Understanding filter()
  4. Examples
    • Basic Usage
    • Using filter() with Complex Conditions
  5. Real-World Use Case
  6. Conclusion

Introduction

The filter() method returns a stream consisting of the elements of the original stream that match a given predicate. This method is an intermediate operation, meaning it returns a new stream and does not modify the original stream.

filter() Method Syntax

The syntax for the filter() method is as follows:

Stream<T> filter(Predicate<? super T> predicate)

Parameters:

  • predicate: A Predicate that represents the condition to be checked against the elements of the stream.

Returns:

  • A new Stream consisting of the elements of the original stream that match the given predicate.

Throws:

  • This method does not throw any exceptions.

Understanding filter()

The filter() method processes each element of the stream and includes it in the resulting stream only if it matches the given predicate. This allows for selective inclusion of elements based on a specified condition.

Examples

Basic Usage

To demonstrate the basic usage of filter(), we will create a Stream and use filter() to include only even numbers.

Example

import java.util.stream.Stream;

public class FilterExample {
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);

        // Use filter() to include only even numbers
        Stream<Integer> evenStream = stream.filter(n -> n % 2 == 0);

        // Print the filtered elements
        evenStream.forEach(System.out::println);
    }
}

Output:

2
4
6

Using filter() with Complex Conditions

This example shows how to use filter() with a complex predicate to include only numbers greater than 3 and even.

Example

import java.util.stream.Stream;

public class ComplexFilterExample {
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Use filter() to include only numbers greater than 3 and even
        Stream<Integer> filteredStream = stream.filter(n -> n > 3 && n % 2 == 0);

        // Print the filtered elements
        filteredStream.forEach(System.out::println);
    }
}

Output:

4
6
8
10

Real-World Use Case

Filtering Out Inactive Users

In real-world applications, the filter() method can be used to filter out inactive users from a stream of user objects based on their status.

Example

import java.util.stream.Stream;

public class FilterInactiveUsersExample {
    static class User {
        String name;
        boolean active;

        User(String name, boolean active) {
            this.name = name;
            this.active = active;
        }

        boolean isActive() {
            return active;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    public static void main(String[] args) {
        Stream<User> users = Stream.of(
            new User("Alice", true),
            new User("Bob", false),
            new User("Charlie", true),
            new User("David", false)
        );

        // Use filter() to include only active users
        Stream<User> activeUsers = users.filter(User::isActive);

        // Print the active users
        activeUsers.forEach(System.out::println);
    }
}

Output:

Alice
Charlie

Conclusion

The Stream.filter() method is used to produce a new stream containing only those elements of the original stream that match a given predicate. This method is particularly useful for selectively including elements based on a specified condition. By understanding and using this method, you can efficiently manage and process streams of values in your Java applications.

Comments