Java 8 – Stream.filter() with Examples

Introduction

Java 8 introduced the Stream API, which provides a powerful and declarative way to process collections of data. One of the most frequently used methods in the Stream API is filter(). The filter() method allows you to extract elements from a stream that match a specific condition or predicate, effectively enabling you to process only the data that meets your criteria.

In this guide, we’ll explore how to use the Stream.filter() method in various scenarios. We’ll provide examples of filtering data in lists, arrays, and custom objects, demonstrating how filter() can simplify and improve the readability of your code.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Filtering a List of Integers
    • Filtering a List of Strings
    • Filtering a Stream of Custom Objects
  • Advanced Considerations
  • Conclusion

Problem Statement

The task is to create a Java program that:

  • Demonstrates how to use the filter() method to extract elements from a stream based on a condition.
  • Applies filter() to different types of data, including lists of integers, strings, and custom objects.
  • Outputs the filtered results.

Example 1:

  • Input: List of integers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], filter even numbers.
  • Output: [2, 4, 6, 8, 10]

Example 2:

  • Input: List of strings ["apple", "banana", "cherry"], filter strings with length greater than 5.
  • Output: ["banana", "cherry"]

Solution Steps

  1. Create a Stream: Start with a stream of elements (e.g., integers, strings, custom objects).
  2. Apply the filter() Method: Use the filter() method to retain only the elements that match a specific condition.
  3. Display the Result: Collect and print the filtered elements.

Java Program

Filtering a List of Integers

The filter() method can be used to filter a list of integers, such as selecting only the even numbers.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Java 8 - Filtering a List of Integers Using Stream.filter()
 * Author: https://www.rameshfadatare.com/
 */
public class FilterIntegerList {

    public static void main(String[] args) {
        // Step 1: Create a list of integers
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Step 2: Filter the list to include only even numbers
        List<Integer> evenNumbers = numbers.stream()
            .filter(n -> n % 2 == 0)
            .collect(Collectors.toList());

        // Step 3: Display the result
        System.out.println("Even Numbers: " + evenNumbers);
    }
}

Output

Even Numbers: [2, 4, 6, 8, 10]

Explanation

  • The numbers.stream() method creates a stream from the list of integers.
  • The filter(n -> n % 2 == 0) method filters the stream, keeping only even numbers.
  • The collect(Collectors.toList()) method collects the filtered numbers into a list.

Filtering a List of Strings

You can use the filter() method to filter a list of strings based on a specific condition, such as string length.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Java 8 - Filtering a List of Strings Using Stream.filter()
 * Author: https://www.rameshfadatare.com/
 */
public class FilterStringList {

    public static void main(String[] args) {
        // Step 1: Create a list of strings
        List<String> fruits = Arrays.asList("apple", "banana", "cherry", "date");

        // Step 2: Filter the list to include only strings with length greater than 5
        List<String> filteredFruits = fruits.stream()
            .filter(fruit -> fruit.length() > 5)
            .collect(Collectors.toList());

        // Step 3: Display the result
        System.out.println("Filtered Fruits: " + filteredFruits);
    }
}

Output

Filtered Fruits: [banana, cherry]

Explanation

  • The fruits.stream() method creates a stream from the list of strings.
  • The filter(fruit -> fruit.length() > 5) method filters the stream, keeping only strings with more than 5 characters.
  • The collect(Collectors.toList()) method collects the filtered strings into a list.

Filtering a Stream of Custom Objects

The filter() method can also be used to filter streams of custom objects. For instance, you might want to filter a list of products based on their price.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Java 8 - Filtering a Stream of Custom Objects Using Stream.filter()
 * Author: https://www.rameshfadatare.com/
 */
public class FilterCustomObjects {

    public static void main(String[] args) {
        // Step 1: Create a list of products
        List<Product> products = Arrays.asList(
            new Product("Laptop", 1500),
            new Product("Phone", 800),
            new Product("Tablet", 600),
            new Product("Smartwatch", 200)
        );

        // Step 2: Filter the list to include only products priced above 500
        List<Product> expensiveProducts = products.stream()
            .filter(product -> product.getPrice() > 500)
            .collect(Collectors.toList());

        // Step 3: Display the result
        expensiveProducts.forEach(product -> 
            System.out.println("Product: " + product.getName() + ", Price: " + product.getPrice()));
    }
}

// Custom class Product
class Product {
    private String name;
    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}

Output

Product: Laptop, Price: 1500.0
Product: Phone, Price: 800.0
Product: Tablet, Price: 600.0

Explanation

  • The products.stream() method creates a stream from the list of Product objects.
  • The filter(product -> product.getPrice() > 500) method filters the stream, keeping only products priced above 500.
  • The filtered products are collected into a list and displayed.

Advanced Considerations

  • Chaining filter() Operations: You can chain multiple filter() operations to apply more complex filtering criteria.

  • Performance Considerations: Filtering large datasets using parallel streams can improve performance, especially when the filtering logic is computationally expensive.

  • Null Handling: Ensure your filtering logic handles null values appropriately, either by filtering them out or by providing a default behavior.

Conclusion

This guide provides methods for using the Stream.filter() method in Java 8, covering different types of data including integers, strings, and custom objects. The filter() method is a powerful feature of the Stream API that allows you to process only the elements that meet your specific criteria, making your code more concise and readable. By understanding how to use filter() effectively, you can improve the efficiency and clarity of your data processing tasks in Java.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top