Stream filter() operation in Java is an intermediate operation, and it is used to filter stream elements based on a given predicate. It accepts Predicate functional interface as an input and returns a Stream.
Syntax
Stream<T> filter(Predicate<? super T> predicate)
Java Stream filter() operation – examples
Example 1:
Create a program that takes a list of Integers, filters all elements, and returns a new list consisting only of even numbers.
class Test { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); List<Integer> filteredNumbers = numbers.stream() .filter(number -> number % 2 == 0) .collect(Collectors.toList()); System.out.println(filteredNumbers); } }
Output: [2, 4, 6, 8, 10]
Example 2:
Let’s create a Student class:
class Student { private String firstName; private String lastName; private String grade; public Student(String firstName, String lastName, String grade) { this.firstName = firstName; this.lastName = lastName; this.grade = grade; } public String getGrade() { return grade; } @Override public String toString() { return "student: {" + firstName + " " + lastName + " " + grade + "} "; } }
Now, let’s filter all students which grade is higher than 7:
class Test { public static void main(String[] args) { List<Student> filteredStudents = getStudents().stream() .filter(student -> student.getGrade() > 7) .collect(Collectors.toList()); System.out.println(filteredStudents); } private static List<Student> getStudents() { List<Student> students = new ArrayList<>(); students.add(new Student("Steve", "Rogers", 8)); students.add(new Student("John", "Doe", 5)); students.add(new Student("Melissa", "Smith", 7)); students.add(new Student("Megan", "Norton", 4)); students.add(new Student("Tom", "Johnson", 9)); return students; } }
Output: [student: {Steve Rogers 8} , student: {Tom Johnson 9} ]
I hope this tutorial was helpful to you. To learn more, check out other Java Functional Programming tutorials.