Java Stream Filter along with Lambda Expression – Complete Guide
JavaStream offers the filter() method that filters stream elements according to a predicate provided. The predicate is taken as an argument and a stream of resulting elements is returned by this method.
Stream filter(predicate) returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation.
These operations are always lazy i.e., Filtering is not actually performed by executing an intermediate operation, such as filter(), instead, it generates a new stream that, when traversed, includes the elements of the previous stream that match the given predicate.
Syntax:
Stream filter(Predicate<? Super T> predicate)
where,
Stream – It is an Interface
T – Type of input to the predicate.
For Example,
1. Let’s create here Person class:
public class Person{
private int id;
private String name;
//constructor and getter method
}
In addition, create a collection of Person class,
Person p1 = new Person(100, “Amit”);
Person p2 = new Person(101, “Tushar”);
Person p3 = new Person(102, “Shubham”);
Person p4 = new Person(103, “Pooja”);
Person p5 = new Person(104, “Nitin”);
List person = Arrays.asList(p1,p2,p3,p4,p5);
2. Filtering the collections:
A common use case of the filter() method is to process collections with a lambda expression,
List per = person.stream()
.filter(p -> p.getID() > 102)
.collect(Collectors.toList());
Let’s Create full example,
import java.util.*;
import java.util.stream.Collectors;
class ProductDetails{
int productID;
String productName;
float productPrice;
public ProductDetails(int pID, String pName, float pPrice) {
this.productID = pID;
this.productName = pName;
this.productPrice = pPrice;
}
}
public class JavaStreamFilterExample {
public static void main(String[] args) {
List productsList = new ArrayList();
//Adding ProductsDetails
productsList.add(new ProductDetails(10,”Lava Mobile”,15000f));
productsList.add(new ProductDetails(20,”Apple Laptop”,90000f));
productsList.add(new ProductDetails(30,”Dell Laptop”,45000f));
productsList.add(new ProductDetails(40,”HP Laptop”,55000f));
productsList.add(new ProductDetails(50,”Samsung Mobile”,25000f));
productsList.add(new ProductDetails(60,”MI Mobile”,18000f));
List productPricesList = productsList.stream()
.filter(p1 ->p1.productPrice> 30000) // filtering price
.map(pm ->pm.productPrice) // fetching price
.collect(Collectors.toList());
System.out.println(productPricesList);
}
}
For more information & classes Call: 2048553004
Registration Link: Click Here!
Author: Ambarish Durani
JAVA Trainer
IT Education Centre Placement & Training Institute
© Copyright 2023 | IT Education Centre.