Updated April 10, 2023
Introduction to Java Stream Filter
Stream.filter() is a method in Java we use while working with streams. It traverses through all the elements present and removes or filters out all those elements that are not matching with the specified condition through a significant argument. This is basically an operation that takes place in between the stream interface. The function returns an output stream having the elements of the input stream matching the given conditions.
The argument passed with the filter() will be a stateless predicate and applies to each and every element to identify if it should be included or not. We can pass lambda expression also through this since the predicate falls under the functional interface category. The output contains a new stream that can be used for any other operations relevant to any stream.
Syntax:
Stream<T> filter(Predicate<? super T> condition)d
Predicate represents a functional interface and shows the condition we use to filter out elements that do not match the stream.
Examples to Implement Java Stream Filter
Let us undertake a few of examples to understand the functionality of the Java stream() function.
Example #1
Code:
import java.util.Arrays;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
List<Integer> arr = Arrays.asList(11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
arr.stream()
.filter(i -> i % 3 == 0)
.forEach(System.out::println);
}
}
Output:
Explanation: This is a very basic and simple example that shows how to use the java stream filter function. In this example, we are declaring an array of random numbers and assigning them to a List. Then we are using the stream filter to filter out all those elements in the given array that satisfy the condition given, i.e. all the numbers in the array that gives a modulus of 3 as 0 are filtered and displayed in the output.
Example #2
Code:
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class Main
{
public static void main(String[] args)
{
List<Integer> arr = Arrays.asList(21, 22, 23, 24, 25, 26, 27, 28, 29, 30);
Predicate<Integer> condition = new Predicate<Integer>()
{
@Override
public boolean test(Integer i) {
if (i % 4 == 0) {
return true;
}
return false;
}
};
arr.stream().filter(condition).forEach(System.out::println);
}
}
Output:
Explanation: In this example, we are first declaring an input array consisting of a random set of numbers and assigning them a list. Here we are also showing how to use and declare predicate along with stream filter function by first creating an object of the same of the name condition. Then a class of the name test having an input parameter of integer I am created where we are checking the modulus of 4 of the given array. This function returns a boolean value of true if modulues of 4 return 0 and false otherwise. By taking this return value, the stream function is then used to fetch the elements from the array whose condition is true.
Example #3
Code:
import java.util.*;
public class Example {
public static void main(String[] args) {
//Array creation
List<String> arr1 = Arrays.asList("trial", "simple", "node");
//Calling usingFiltOutput function
List<String> op = usingFiltOutput(arr1, "node");
//for loop to print array
for (String arr : op) {
System.out.print(arr);
System.out.print("\n");
}
}
private static List<String> usingFiltOutput(List<String> arr2, String filter) {
List<String> op = new ArrayList<>();
for (String arr1 : arr2) {
if (!"node".equals(arr1)) {
op.add(arr1);
}
}
return op;
}
}
Output:
Explanation: In the above example, we are showing the filtering of array elements where we are filtering the element “node” by using the stream filter method
Example #4
Code:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Car> listCar = new ArrayList<>();
listCar.add(new Car("Maruti", 350000));
listCar.add(new Car("Toyota", 400000));
listCar.add(new Car("Mahindra", 500000));
listCar.add(new Car("Honda", 600000));
// displaying all cars with cost more than 4lakh
listCar.stream().filter(c -> (c.getID() > 400000))
.forEach(c -> System.out.println(c.getCompany()));
}
}
class Car {
private String company;
private int ID;
public Car() {
}
public Car(String n, int a) {
this.company = n;
this.ID = a;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
}
Output:
Explanation: In this example, we shall see a kind of a real-time application where the list of different companies of cars and their basic cost has been assigned to an array list as shown. Then we are defining a few methods below to fetch the individual values from the array list. getcost method is used to get the cost of that particular car, and getCompany is used to get the company name from the input array list. Then in the main function, we are using the Java stream filter function to fetch only those car company names whose approximate cost falls above Rs.400000.
Example #5
Code:
import java.util.*;
import java.util.stream.Collectors;
class Example{
int pro_id;
String pro_name;
float pro_cost;
public Example(int pro_id, String pro_name, float pro_cost) {
this.pro_id = pro_id;
this.pro_name = pro_name;
this.pro_cost = pro_cost;
}
}
public class JavaStreamExample {
public static void main(String[] args) {
List<Example> productsList = new ArrayList<Example>();
//Here we are listing the products
productsList.add(new Example(1,"Shirt",1500f));
productsList.add(new Example(2,"Long Sleeve Top",1000f));
productsList.add(new Example(3,"Crop Top",1600f));
productsList.add(new Example(4,"Jeans",2100f));
productsList.add(new Example(5,"Skirt",1800f));
List<Float> pricesList = productsList.stream()
.filter(p ->p.pro_cost> 1500)
.map(pm ->pm.pro_cost)
.collect(Collectors.toList());
System.out.println(pricesList);
}
}
Output:
Explanation: In this example, we are first declaring out a few parameters regarding the products of a dress shop, such as product id, name, and cost. And by using the ArrayList, we are adding certain products into it along with its parameters. In the end, by using the java stream filter, we are filtering out a few products whose cost is above Rs.1500. This shows a real-time application of this method.
Conclusion
We saw all the different kinds of combinations with which the Java stream filter can be used to filter out certain elements in the array based on the condition we give. It can also be combined with Java streams, array lists, collections, and many others based on the requirement.
Recommended Articles
This is a guide to Java Stream Filter. Here we discuss an introduction to the Java stream() function with respective examples to understand the functionality. You can also go through our other related articles to learn more –