Java 8 – Filter a Stream Using Lambda Expressions

Introduction

Filtering a stream is a fundamental operation in Java, especially when you need to extract elements from a collection that match specific criteria. Java 8 introduced the Stream API, which provides a powerful way to process data in a declarative manner. One of the key features of the Stream API is the ability to filter data using lambda expressions, allowing you to define custom conditions in a concise and readable way. In this guide, we’ll explore how to filter a stream using lambda expressions in Java 8, covering various scenarios and use cases.

Table of Contents

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

Problem Statement

The task is to create a Java program that:

  • Accepts a collection of elements.
  • Filters the collection using a lambda expression based on specific criteria.
  • Outputs the filtered elements.

Example 1:

  • Input: List of integers [1, 2, 3, 4, 5, 6], Filter: Even numbers
  • Output: Filtered list [2, 4, 6]

Example 2:

  • Input: List of strings ["apple", "banana", "avocado"], Filter: Strings starting with "a"
  • Output: Filtered list ["apple", "avocado"]

Solution Steps

  1. Create a Collection: Start with a collection of elements that you want to filter.
  2. Filter the Collection Using Lambda Expressions: Use the Stream API and filter() method to filter the collection based on the lambda expression.
  3. Display the Result: Print the filtered elements.

Java Program

Filtering a Stream of Integers

Filtering a list of integers to extract even numbers is a simple and common use case. Here’s how you can do it using a lambda expression.

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

/**
 * Java 8 - Filter a Stream of Integers Using Lambda Expressions
 * Author: https://www.rameshfadatare.com/
 */
public class FilterStreamOfIntegers {

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

        // 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]

Explanation

  • The stream() method creates a stream from the list of integers.
  • The filter(n -> n % 2 == 0) method uses a lambda expression to filter out all odd numbers, keeping only even numbers.
  • The filtered numbers are collected into a list using Collectors.toList() and printed.

Filtering a Stream of Strings

You can also filter a list of strings, for example, to include only those that start with a specific letter.

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

/**
 * Java 8 - Filter a Stream of Strings Using Lambda Expressions
 * Author: https://www.rameshfadatare.com/
 */
public class FilterStreamOfStrings {

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

        // Step 2: Filter the list to include only strings starting with "a"
        List<String> filteredFruits = fruits.stream()
            .filter(fruit -> fruit.startsWith("a"))
            .collect(Collectors.toList());

        // Step 3: Display the result
        System.out.println("Fruits starting with 'a': " + filteredFruits);
    }
}

Output

Fruits starting with 'a': [apple, avocado]

Explanation

  • The stream() method creates a stream from the list of strings.
  • The filter(fruit -> fruit.startsWith("a")) method filters the stream to include only strings that start with the letter "a".
  • The filtered strings are collected into a list using Collectors.toList() and printed.

Filtering a Stream of Custom Objects

Filtering a stream of custom objects, such as filtering students based on their age, is another common use case.

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

/**
 * Java 8 - Filter a Stream of Custom Objects Using Lambda Expressions
 * Author: https://www.rameshfadatare.com/
 */
public class FilterStreamOfCustomObjects {

    public static void main(String[] args) {
        // Step 1: Create a list of students
        List<Student> students = List.of(
            new Student("Raj", 25),
            new Student("Anita", 30),
            new Student("Vikram", 22)
        );

        // Step 2: Filter the list to include only students older than 25
        List<Student> filteredStudents = students.stream()
            .filter(student -> student.getAge() > 25)
            .collect(Collectors.toList());

        // Step 3: Display the result
        filteredStudents.forEach(student -> 
            System.out.println(student.getName() + ": " + student.getAge())
        );
    }
}

// Custom class Student
class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Output

Anita: 30

Explanation

  • The stream() method creates a stream from the list of Student objects.
  • The filter(student -> student.getAge() > 25) method filters the stream to include only students older than 25.
  • The filtered students are collected into a list using Collectors.toList() and printed.

Advanced Considerations

  • Complex Conditions: Lambda expressions can be as simple or as complex as needed. You can combine multiple conditions using logical operators like && and ||.

  • Parallel Streams: If you are working with large datasets, consider using parallel streams (parallelStream()) to improve performance when filtering.

  • Immutable Collections: If you need the filtered list to be immutable, you can wrap the result with Collections.unmodifiableList() after collecting it.

Conclusion

This guide provides methods for filtering a stream using lambda expressions in Java 8, covering scenarios with integers, strings, and custom objects. The Stream API, combined with lambda expressions, offers a powerful and concise way to filter data based on specific criteria. Depending on your specific use case, you can choose the method that best fits your needs for filtering streams in Java.

Leave a Comment

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

Scroll to Top