In this post, we are going to see Java 8 Stream filter() examples. The filter()
method is used to filter elements from a stream based on a given condition. It takes Predicate
as an argument, which is a functional interface that defines a test for each element in the stream.
It creates a new stream containing only the elements that satisfy the provided condition. Here are some examples of how to use the filter()
method in Java 8.
Filtering even numbers from a list
package com.javatute.stream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class JavaStreamFilterExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(35);
list.add(5);
list.add(33);
list.add(24);
list.add(3);
list.add(20);
System.out.println(list);
List<Integer> evenNumbers = list.stream().filter(n -> n % 2 == 0).collect(Collectors.toList());
System.out.println(evenNumbers);
}
}
Output:-
[10, 35, 5, 33, 24, 3, 20]
[10, 24, 20]
Without Java 8 and with Java 8 Stream filter() Examples
For a better understanding, here we have a few examples of using the Java 8 Stream filter()
method, both without Java 8 and with Java 8.
Example 1: Filtering even numbers from a List
Without Java 8:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> evenNumbers = new ArrayList<>();
for (Integer num : numbers) {
if (num % 2 == 0) {
evenNumbers.add(num);
}
}
System.out.println(evenNumbers);
With Java 8:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> evenNumbers = numbers.stream()
.filter(num -> num % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers);
In the first example (without Java 8), we loop through the list of numbers and manually filter out even numbers, adding them to a new list. In the second example (with Java 8), we use the filter()
method to create a stream of numbers, apply a lambda expression to filter out even numbers, and collect the results into a new list.
Example 2: Filtering strings that start with a specific letter
Without Java 8:
List<String> words = Arrays.asList("apple", "banana", "cherry", "date");
List<String> filteredWords = new ArrayList<>();
for (String word : words) {
if (word.startsWith("a")) {
filteredWords.add(word);
}
}
System.out.println(filteredWords);
With Java 8:
List<String> words = Arrays.asList("apple", "banana", "cherry", "date");
List<String> filteredWords = words.stream()
.filter(word -> word.startsWith("a"))
.collect(Collectors.toList());
System.out.println(filteredWords);
In this example, we filter strings that start with the letter “a.” Without Java 8, we iterate through the list and manually check each element’s starting letter. With Java 8, we use the filter()
method and a lambda expression to achieve the same result more concisely.
Example 3: Filtering objects by a custom condition
Without Java 8:
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 22)
);
List<Person> filteredPeople = new ArrayList<>();
for (Person person : people) {
if (person.getAge() >= 25) {
filteredPeople.add(person);
}
}
System.out.println(filteredPeople);
With Java 8:
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 22)
);
List<Person> filteredPeople = people.stream()
.filter(person -> person.getAge() >= 25)
.collect(Collectors.toList());
System.out.println(filteredPeople);
In this example, we filter a list of Person
objects based on a custom condition (age greater than or equal to 25). Without Java 8, we iterate through the list and manually check the condition. With Java 8, we use the filter()
method and a lambda expression to filter objects based on the condition.
Example 4: Filtering unique elements from a List
Without Java 8:
List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
Set<Integer> uniqueNumbers = new HashSet<>();
for (Integer num : numbers) {
uniqueNumbers.add(num);
}
System.out.println(uniqueNumbers);
With Java 8:
List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
List<Integer> uniqueNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(uniqueNumbers);
In this example, we filter unique elements from a list of numbers. Without Java 8, we manually create a Set
to store unique values. With Java 8, we use the distinct()
method to filter unique elements from the stream and collect them into a list.
Example 5: Filtering files in a directory
Without Java 8:
File[] files = new File("/path/to/directory").listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isFile();
}
});
for (File file : files) {
System.out.println(file.getName());
}
With Java 8:
File[] files = new File("/path/to/directory").listFiles(File::isFile);
Arrays.stream(files)
.map(File::getName)
.forEach(System.out::println);
In this example, we filter files in a directory that are considered as files (not directories). Without Java 8, we use an anonymous inner class implementing FileFilter
. With Java 8, we use method references and stream operations to filter and print file names more concisely.
Java 8 Stream filter() examples – Real-time use cases
1. We are going to convert below old Java code to Java 8 using the Stream filter() method
Set<MyApplication> appsToBeRetained = new HashSet<>();
for (MyApplication myApp : fromDatabase.getMyApplications()) {
if (myApp.getMyAccount() != null &&
myApp.getMyAccount().getAccountId() != null &&
myApp.getMyAccount().getAccountId().equals(newEntity.getId()) &&
!myApp.getStatusInfo().isMarkedForDeletion()) {
appsToBeRetained.add(myApp);
}
}
Using Java 8
Set<MyApplication> appsToBeRetained =
fromDatabase.getMyApplications().stream()
.filter(myApp ->
myApp.getMyAccount() != null &&
myApp.getMyAccount().getAccountId() != null &&
myApp.getMyAccount().getAccountId().equals(newEntity.getId()) &&
!myApp.getStatusInfo().isMarkedForDeletion())
.collect(Collectors.toSet())
: new HashSet<>();
2. Another Java 8 Stream filter() example
Without java 8
Set<Long> selectedAccountIds = new HashSet<>();
Set<YourAccountTree> parentAccountTrees = someEntity.getParentTree();
YourAccountTree callingUserAccountTree = null;
for (YourAccountTree tree : parentAccountTrees) {
if (tree.getParentId().equals(callingUsersAccountId)) {
callingUserAccountTree = tree;
break;
}
}
The same logic using Java 8
Set<Long> selectedAccountIds = new HashSet<>();
Set<YourAccountTree> parentAccountTrees = someEntity.getParentTree();
YourAccountTree callingUserAccountTree = parentAccountTrees.stream()
.filter(tree -> tree.getParentId().equals(callingUsersAccountId))
.findAny()
.orElse(null);
Ten objective questions related to Java 8 Stream filter() examples.
Here are 10 objective questions related to the Java 8 filter()
method, along with four options for each question. The correct answers are provided at the end.
Question 1: What is the primary purpose of the filter()
method in Java 8 Streams?
A) To perform sorting operations on a stream.
B) To transform elements in a stream to a different data type.
C) To select elements from a stream based on a specified condition.
D) To concatenate multiple streams into one.
Question 2: Which interface is commonly used as a parameter for the filter()
method to specify the filtering condition?
A) Function
B) Predicate
C) Comparator
D) Consumer
Question 3: In Java 8, what does the filter()
method return after applying a filtering condition to a Stream?
A) A new Stream containing the filtered elements.
B) An array containing the filtered elements.
C) A List containing the filtered elements.
D) An element from the filtered Stream.
Question 4: Which of the following is a valid use case for the filter()
method in Java 8?
A) Converting a Stream of integers to strings.
B) Sorting a Stream of elements in ascending order.
C) Selecting all elements from a Stream without any condition.
D) Filtering out even numbers from a Stream of integers.
Question 5: How do you filter unique elements from a Stream using the filter()
method?
A) Use the filterDistinct()
method.
B) Use the distinct()
method after filter()
.
C) Apply a custom filter condition using filter()
.
D) Use the unique()
method after filter()
.
Question 6: In Java 8, what is the return type of the filter()
method when applied to a Stream?
A) Stream
B) List
C) Set
D) Array
Question 7: Which of the following is true about the filter()
method in Java 8?
A) It modifies the original Stream in place.
B) It can only be used on collections, not on Streams.
C) It creates a new Stream containing the filtered elements.
D) It throws an exception if the filtering condition is not met.
Question 8: When using the filter()
method, what type of function does the lambda expression typically represent?
A) Transformation function
B) Sorting function
C) Filtering condition
D) Aggregation function
Question 9: How can you apply multiple filtering conditions to a Stream using the filter()
method in Java 8?
A) You cannot apply multiple conditions with filter()
.
B) Chain multiple filter()
operations.
C) Use the applyConditions()
method.
D) Create a custom filter function.
Question 10: What is the result of applying the filter()
method to an empty Stream in Java 8?
A) An empty Stream.
B) Null.
C) An exception is thrown.
D) A single element with a default value.
Answers:
1) C) To select elements from a stream based on a specified condition.
2) B) Predicate
3) A) A new Stream containing the filtered elements.
4) D) Filtering out even numbers from a Stream of integers.
5) B) Use the distinct()
method after filter()
.
6) A) Stream
7) C) It creates a new Stream containing the filtered elements.
8) C) Filtering condition
9) B) Chain multiple filter()
operations.
10) A) An empty Stream.
That’s all about Java 8 Stream filter() examples.
See docs.
Other Java 8 examples.
- Difference between Anonymous Inner Class and Lambda Expression
- Java 8 Comparator comparing() example
- Java 8 Lambda Expressions Examples
- Write a program to find the nth Highest Salary using Java…
- Java 8 Functional Interface Examples
- Java 8 Supplier Examples
- Java 8 Consumer Examples
- Java 8 Predicate examples
- Java 8 default methods examples
- Java 8 Collection vs Stream
- Java 8 static methods examples
- Java 8 Method Reference Examples
- Java 8 Function interface Examples
- Java Stream filter() vs map()