Java Streaming API | Filtering elements from the streams
So, Todays we are going to learn how to filter out the unwanted elements from the Streams of any collection. Let's get Started on It
Let's start with a basic example and we can dig deeper to explain it in more detail. In the Below example, I would like to remove all old cars who manufactured 5 years before.
Detailed Version Code
public class JavaStreamingApiFilteringExample {
public static void main(String args[]) {
List<Car> listOfCars = Arrays.asList(
new Car("MH12 AB1234", 1, "Mercedes GLS 350d"),
new Car("IN32 AB1234", 2, "Audi q7"),
new Car("DL78 AB1234", 3, "Ferrari 488"),
new Car("NY99 AB1234", 4, "rolls royce phantom"),
new Car("CA76 AB1234", 5, "Ford GT"),
new Car("EN90 AB1234", 6, "Lamborghini"),
new Car("CA56 AB1234", 7, "Porsche 911 GT2 RS"),
new Car("US34 AB1234", 8, "Nissan GT-R"),
new Car("MX11 AB1234", 9, "Aston Martin DBS"),
new Car("EU65 AB1234", 10, "Range Rover"));
List<Car> carWithAgeLessThan5Years = listOfCars
.stream()
.filter(new Predicate<Car>() { // Long ways of Writing code, See improved version below with lambda functiona
@Override
public boolean test(Car car) {
// Since we need car with less than 5 year old. every other cars
// which will not satisfy this condition will get filtered out
return car.getAge() < 5;
}
})
.collect(Collectors.toList());
System.out.println(carWithAgeLessThan5Years);
}
}
class Car {
private String number;
private int age;
private String model;
// constructor, getter, setters and toString methods}
Concise version code (Using lambda function)
public class JavaStreamingApiFilteringExample {
public static void main(String args[]) {
List<Car> listOfCars = Arrays.asList(
new Car("MH12 AB1234", 1, "Mercedes GLS 350d"),
new Car("IN32 AB1234", 2, "Audi q7"),
new Car("DL78 AB1234", 3, "Ferrari 488"),
new Car("NY99 AB1234", 4, "rolls royce phantom"),
new Car("CA76 AB1234", 5, "Ford GT"),
new Car("EN90 AB1234", 6, "Lamborghini"),
new Car("CA56 AB1234", 7, "Porsche 911 GT2 RS"),
new Car("US34 AB1234", 8, "Nissan GT-R"),
new Car("MX11 AB1234", 9, "Aston Martin DBS"),
new Car("EU65 AB1234", 10, "Range Rover"));
List<Car> carWithAgeLessThan5Years = listOfCars
.stream()
.filter( c -> c.getAge() < 5)
.collect(Collectors.toList());
System.out.println(carWithAgeLessThan5Years);
}
}
What is Predicate Interface?
In Java 8, Predicate is a functional interface, which accepts an argument and returns a boolean. Usually, it used to apply in a filter for a collection of objects.
References :
Java DOC for Predicate interaface
0 comments:
Post a Comment