In this guide, you will learn about the Stream filter() method in Java programming and how to use it with an example.
1. Stream filter() Method Overview
Definition:
The Stream.filter() method is used to filter elements of a stream based on a given predicate (a condition). It returns a new stream consisting of elements that satisfy the specified predicate.
Syntax:
Stream<T> filter(Predicate<? super T> predicate)
Parameters:
- predicate: The condition (as an instance of Predicate) based on which elements are included in the resulting stream.
Key Points:
- The filter() method does not modify the original stream. Instead, it returns a new stream that contains elements satisfying the given predicate.
- The resulting stream retains the order of elements from the original stream.
- If the stream has been parallelized, the filter operation is also parallelized.
- This operation is an intermediate operation, which means it can be chained with other stream operations.
2. Stream filter() Method Example 1
import java.util.stream.Stream;
public class StreamFilterExample {
public static void main(String[] args) {
Stream<String> namesStream = Stream.of("Alice", "Bob", "Charlie", "Dave", "Eve");
// Using filter to get names that start with the letter 'A' or 'E'
Stream<String> filteredNames = namesStream.filter(name -> name.startsWith("A") || name.startsWith("E"));
filteredNames.forEach(System.out::println);
}
}
Output:
Alice Eve
Explanation:
In the given example, we have a stream of names. We use the filter() method to retain only those names that start with the letter 'A' or 'E'. The resulting filtered stream is then printed using the forEach method, showing the names "Alice" and "Eve".
3. Stream filter() Method Example 2
import java.util.ArrayList;
import java.util.List;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class Main {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Ramesh", 25));
people.add(new Person("Pramod", 30));
people.add(new Person("Somu", 20));
// Filter people who are older than 25
List<Person> filteredPeople = people.stream()
.filter(person -> person.getAge() > 25)
.toList();
// Print the filtered people
filteredPeople.forEach(person -> System.out.println(person.getName()));
}
}
Output:
Pramod
Comments
Post a Comment
Leave Comment