The filter()
method in Java is a part of the java.util.stream.Stream
interface. In this guide, we will learn how to use filter()
method in Java with practical examples and real-world use cases to better understand its usage.
Table of Contents
- Introduction
filter()
Method Syntax- Understanding
filter()
- Examples
- Basic Usage
- Using
filter()
with Complex Conditions
- Real-World Use Cases
- Conclusion
Introduction
The Stream.filter()
method in Java is used to select elements that match a given condition. It filters the stream based on a predicate.
This method is useful when you want to process only specific elements from the stream that meet certain criteria.
filter()
is commonly used in stream operations to refine the data before applying further transformations or collecting the result.
filter()
Method Syntax
Here’s the syntax for the filter()
method:
Stream<T> filter(Predicate<? super T> predicate)
Parameters:
predicate
: APredicate
that defines the condition against which elements of the stream are tested.
Returns:
- A new
Stream
that contains elements matching the given condition.
Throws:
- The
filter()
method doesn’t throw any exceptions directly but might propagate exceptions from the predicate used.
Understanding filter()
The filter()
method evaluates each element in the stream and includes it in the new stream only if it satisfies the condition specified in the predicate. This method helps you selectively filter elements from a large dataset or collection.
Examples
Basic Usage
Let’s start with a simple example where we filter out only even numbers from a stream:
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
In this example, we’ll filter numbers that are both greater than 3 and even.
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);
// Filter 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 Cases
Example 1: Filtering Inactive Users
Let’s say you’re working with a list of users and want to filter out inactive users based on their status.
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)
);
// Filter only active users
Stream<User> activeUsers = users.filter(User::isActive);
// Print the active users
activeUsers.forEach(System.out::println);
}
}
Output:
Alice
Charlie
Example 2: Filtering Products by Price and Availability
Suppose you have a product list and want to filter products that are priced above ₹500 and are available in stock.
import java.util.stream.Stream;
public class FilterProductsExample {
static class Product {
String name;
double price;
boolean inStock;
Product(String name, double price, boolean inStock) {
this.name = name;
this.price = price;
this.inStock = inStock;
}
boolean isInStock() {
return inStock;
}
double getPrice() {
return price;
}
@Override
public String toString() {
return name;
}
}
public static void main(String[] args) {
Stream<Product> products = Stream.of(
new Product("Laptop", 60000, true),
new Product("Phone", 25000, true),
new Product("Headphones", 1500, false),
new Product("Monitor", 8000, true)
);
// Filter products priced over ₹500 and available in stock
Stream<Product> filteredProducts = products.filter(p -> p.getPrice() > 500 && p.isInStock());
// Print the filtered products
filteredProducts.forEach(System.out::println);
}
}
Output:
Laptop
Phone
Monitor
Example 3: Filtering Employees by Age and Department
In this example, we filter employees who are older than 30 and work in the “Engineering” department.
import java.util.stream.Stream;
public class FilterEmployeesExample {
static class Employee {
String name;
int age;
String department;
Employee(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}
int getAge() {
return age;
}
String getDepartment() {
return department;
}
@Override
public String toString() {
return name + " (" + age + ", " + department + ")";
}
}
public static void main(String[] args) {
Stream<Employee> employees = Stream.of(
new Employee("Rajesh", 35, "Engineering"),
new Employee("Anita", 28, "HR"),
new Employee("Vikram", 40, "Engineering"),
new Employee("Meera", 25, "Sales")
);
// Filter employees older than 30 and in the Engineering department
Stream<Employee> filteredEmployees = employees.filter(e -> e.getAge() > 30 && e.getDepartment().equals("Engineering"));
// Print the filtered employees
filteredEmployees.forEach(System.out::println);
}
}
Output:
Rajesh (35, Engineering)
Vikram (40, Engineering)
Conclusion
The Stream.filter()
method allows you to process collections or streams based on custom conditions using predicates. It’s highly useful for filtering data, especially in real-world applications, where you can remove unnecessary elements and work only with the relevant data. By leveraging this method, you can easily write more efficient and maintainable Java code.