Java 8 Stream – filter() & forEach() Example
Hello. In this tutorial, we will explain the most commonly used Java 8 Stream APIs: the forEach() and filter() methods.
1. Introduction
Before diving deep into the practice stuff let us understand the forEach
and filter
methods.
1.1 forEach method
This method is used to iterate the elements present in the collection such as List, Set, or Map. It is a default method present in the Iterable interface and accepts a single argument thereby acting as a functional interface in Java. Represented by the syntax –
forEach() method
default void forEach(Consumer<super T>action)
1.2 filter method
This method is used to refine the stream of elements based on a given condition. Assume you have to print only odd elements from an integer collection then you will use this method. The method accepts the condition as an argument and returns a new stream of refined elements. Represented by the syntax –
filter() method
Stream<T> filter(Predicate<? super T> predicate)
where –
predicate
denotes the condition and is a functional interface so it can also be passed as a lambda expression
2. Practice
Let us dive into some practice stuff from here and I am assuming that you already have the Java 1.8 or greater installed in your local machine. I am using JetBrains IntelliJ IDEA as my preferred IDE. You’re free to choose the IDE of your choice.
2.1 Model class
Create a java file in the com.assignment.util
package and add the following content to it.
Student.java
package com.assignment.util; import java.util.ArrayList; import java.util.List; public final class Student { private final int id; private final String name; private final double cgpa; private Student(final int id, final String name, final double cgpa) { this.id = id; this.name = name; this.cgpa = cgpa; } //util method public static List<Student> createStudents() { final List<Student> students = new ArrayList<>(); //adding students students.add(new Student(101, "John P.", 7.51)); students.add(new Student(102, "Sarah M.", 9.67)); students.add(new Student(103, "Charles B.", 4.5)); students.add(new Student(104, "Mary T.", 8.7)); return students; } public int getId() { return id; } public String getName() { return name; } public double getCgpa() { return cgpa; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", cgpa=" + cgpa + '}'; } }
2.2 forEach implementation
Create a java file in the com.assignment
package and add the following content to it. The file will consist of two methods consisting of the dummy collection which is iterated upon and each element is console logged.
Java8ForEachExample.java
package com.assignment; import com.assignment.util.Student; import java.util.Arrays; import java.util.List; public class Java8ForEachExample { //forEach() method is used to iterate the elements defined in the iterable and stream interface. //syntax - default void forEach(Consumer<super T>action) //method #2 private static void iterateCollection() { final List<String> names = Arrays.asList("John", "Adam", "Patrick", "Melisandre", "Sansa", "Daenerys"); System.out.println("------------Iterating by passing method reference---------------"); names .stream() .forEach(System.out::println); //printing the results } //method #2 private static void iterateStudentCollection() { System.out.println("------------Iterating by passing lambda expression--------------"); Student.createStudents() .stream() .forEach(student -> System.out.println(student.toString())); //printing the results } public static void main(String[] args) { iterateCollection(); iterateStudentCollection(); } }
Run the file and if everything goes well the following output will be logged in the IDE console.
Console output
------------Iterating by passing method reference--------------- John Adam Patrick Melisandre Sansa Daenerys ------------Iterating by passing lambda expression-------------- Student{id=101, name='John P.', cgpa=7.51} Student{id=102, name='Sarah M.', cgpa=9.67} Student{id=103, name='Charles B.', cgpa=4.5} Student{id=104, name='Mary T.', cgpa=8.7}
2.3 filter implementation
Create a java file in the com.assignment
package and add the following content to it. The file will consist of three different methods consisting of the dummy collection where each collection will pass through a filter method. The filter method will contain a business logic condition and return a new stream of filtered collection.
Java8FilterExample.java
package com.assignment; import com.assignment.util.Student; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Java8FilterExample { //filter() method in java8 programming is used to filter the elements on the basis of a given predicate. //syntax - Stream<T> filter(Predicate<? super T> predicate) //where predicate parameter takes predicate reference as an argument (i.e. a lambda expression) //method #1 private static void filterCollection() { final List<String> names = Arrays.asList("John", "Adam", "Patrick", "Melisandre", "Sansa", "Daenerys"); names .stream() .filter(name -> name.length() > 5) //filtering long names .forEach(System.out::println); //printing the results } //method #2 private static void filterStudentCollectionAndCollect() { final List<Student> students = Student.createStudents(); final List<Student> filteredStudents = students .stream() .filter(student -> student.getCgpa() > 7.0) //filtering students whose cgpa is greater than 7.0 .collect(Collectors.toList()); filteredStudents.forEach(student -> System.out.println(student.toString())); //printing the results } //method #3 private static void filterStudentCollectionWithMultipleCriteria() { final List<Student> students = Student.createStudents(); final Student student = students .stream() .filter(stu -> stu.getCgpa() > 7.0) //filtering students whose cgpa is greater than 7.0 .filter(stu1 -> stu1.getName().startsWith("Mary T.")) //filtering student whose name is Mary T. .findAny() .orElse(null); System.out.println(student.toString()); } //main() method for execution public static void main(String[] args) { filterCollection(); System.out.println("---------------------------"); filterStudentCollectionAndCollect(); System.out.println("---------------------------"); filterStudentCollectionWithMultipleCriteria(); } }
Run the file and if everything goes well the following output will be logged in the IDE console.
Console output
Patrick Melisandre Daenerys --------------------------- Student{id=101, name='John P.', cgpa=7.51} Student{id=102, name='Sarah M.', cgpa=9.67} Student{id=104, name='Mary T.', cgpa=8.7} --------------------------- Student{id=104, name='Mary T.', cgpa=8.7}
That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
3. Summary
In this tutorial, we learned the implementation of forEach
and filter
methods introduced in Java8 Stream API. You can download the source code from the Downloads section.
4. Download the Eclipse Project
This was a tutorial of learning and implementing the forEach
and filter
methods introduced in Java8 Stream API.
You can download the full source code of this example here: Java 8 Stream – filter() and forEach() Example