Tuesday, August 20, 2019

Java 8 Streams filter() - Working Examples

1. Overview


In this tutorial, We'll learn about the new Java 8 Streams API filter() method. This filter method is the one mostly used in streams. Streams build the operations sequentially and parallel.

filter() method takes Predicate which holds a condition. If the condition is true then this element is passed to the next operation in the stream.


We will discuss with example programs so that you can understand clearly.

First, will talk about syntax, examples and how it works internally.



2. Stream API filter() Syntax


Below is the syntax from API.

Stream<T> filter(Predicate<? super T> predicate)

Returns a stream consisting of the elements of this stream that match the given predicate.

This method returns a new Stream. the newly created stream will contain elements that satisfy the predicate condition.

This Predicate can be any condition. Few examples on the predicate.

Predicate<String> namePredicate = s -> s.startsWith("JH");
Predicate<Integer> evenPredicate = i -> i%2 == 0;

filter() method is part of Stream Intermediate Operations.

3. Streams filter() and Collect() methods examples


We will write a program before and in java 8.

Creating a Car class with brandName, modelName, manfactureYear, and fuelType.


class Car{
private String brandName;
private String modelName;
private int manfactureYear;
private String fuelType;


public Car(String brandName, String modelName, int manfactureYear, String fuelType) {
this.brandName = brandName;
this.modelName = modelName;
this.manfactureYear = manfactureYear;
this.fuelType = fuelType;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public int getManfactureYear() {
return manfactureYear;
}
public void setManfactureYear(int manfactureYear) {
this.manfactureYear = manfactureYear;
}
public String getFuelType() {
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
@Override
public String toString() {
return "Car [brandName=" + brandName + ", modelName=" + modelName + ", manfactureYear=" + manfactureYear
+ ", fuelType=" + fuelType + "]";
}

}

We will try to find the values by brandName = Suziki.

3.1 Before Java 8



package com.java.w3schools.blog.java8.streams;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

/**
 * 
 * Java 8 Streams filter() - Working Examples
 * 
 * @author Venkatesh
 *
 */
public class StreamFilterExamplesBeforeJava8 {

public static void main(String[] args) {

List<Car> carsList = getCarsList();
List<Car> suzikiCarsList = new ArrayList<>();
for (Car car : carsList) {
if (car.getBrandName().equals("Suziki")) {
suzikiCarsList.add(car);
}
}

System.out.println("Suziki cars list : " + suzikiCarsList);

}

private static List<Car> getCarsList() {
Car ciazCar = new Car("Suziki", "Ciaz", 2019, "D");
Car dezireCar = new Car("Suziki", "Dezire", 2018, "P");
Car swiftCar = new Car("Suziki", "Swift", 2012, "D");
Car aspireCar = new Car("Ford", "Aspire", 2019, "D");
Car figoCar = new Car("Ford", "Figo", 2015, "P");
Car amazeCar = new Car("Honda", "Amaze", 2017, "D");
Car vernaCar = new Car("Hyundai", "Verna", 2018, "P");

List<Car> carsList = new ArrayList<>();
carsList.add(ciazCar);
carsList.add(dezireCar);
carsList.add(swiftCar);
carsList.add(aspireCar);
carsList.add(figoCar);
carsList.add(amazeCar);
carsList.add(vernaCar);

return carsList;
}

}

Output:

Suziki cars list : [Car [brandName=Suziki, modelName=Ciaz, manfactureYear=2019, fuelType=D], Car [brandName=Suziki, modelName=Dezire, manfactureYear=2018, fuelType=P], Car [brandName=Suziki, modelName=Swift, manfactureYear=2012, fuelType=D]]


3.2 Using Java 8 Streams api - filter() & collect()


List<Car> carsList = getCarsList();
List<Car> suzikiList = carsList.stream().filter(car -> car.getBrandName().equals("Suziki"))
.collect(Collectors.toList());
System.out.println("In Java 8, Suziki cars list : " + suzikiList);

Output:

In Java 8, Suziki cars list : [Car [brandName=Suziki, modelName=Ciaz, manfactureYear=2019, fuelType=D], Car [brandName=Suziki, modelName=Dezire, manfactureYear=2018, fuelType=P], Car [brandName=Suziki, modelName=Swift, manfactureYear=2012, fuelType=D]]

See the output is the same before java 8.

Java 8 makes the code more clear and precise. And also easy to maintain for new changes.

If you want to find out the cars that are manufactured in 2019.

List<Car> cars2019List = carsList.stream().filter( car -> car.getManfactureYear() == 2019).collect(Collectors.toList());
System.out.println("Cars count manufacture in 2019 : "+cars2019List.size());]


Output:

Cars count manufacture in 2019 : 2

4. Streams filter(), map() examples


Find the all diesel car names and retrieve them in Set.

package com.java.w3schools.blog.java8.streams;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 
 * Java 8 Streams filter() and map() - Working Examples
 * 
 * @author Venkatesh
 *
 */
public class StreamFilterExamples {

public static void main(String[] args) {

Predicate<String> namePredicate = s -> s.startsWith("JH");
Predicate<Integer> evenPredicate = i -> i % 2 == 0;

List<Car> carsList = getCarsList();
Set<String> modelnamesList = carsList.stream().filter(car -> car.getFuelType().equals("D"))
.map(Car::getModelName).collect(Collectors.toSet());
modelnamesList.forEach(System.out::println);

}

private static List<Car> getCarsList() {
Car ciazCar = new Car("Suziki", "Ciaz", 2019, "D");
Car dezireCar = new Car("Suziki", "Dezire", 2018, "P");
Car swiftCar = new Car("Suziki", "Swift", 2012, "D");
Car aspireCar = new Car("Ford", "Aspire", 2019, "D");
Car figoCar = new Car("Ford", "Figo", 2015, "P");
Car amazeCar = new Car("Honda", "Amaze", 2017, "D");
Car vernaCar = new Car("Hyundai", "Verna", 2018, "P");

List<Car> carsList = new ArrayList<>();
carsList.add(ciazCar);
carsList.add(dezireCar);
carsList.add(swiftCar);
carsList.add(aspireCar);
carsList.add(figoCar);
carsList.add(amazeCar);
carsList.add(vernaCar);

return carsList;
}
}

Output:

Amaze
Swift
Aspire
Ciaz


5. Multiple conditions in filter predicate


Find the first diesel car name in Suziki brand. Here, We have two conditions and both should be specified in the predicate.

This can be done using filter(), map() and findFirst() methods from stream.

public class StreamFilterExamples {

public static void main(String[] args) {

Optional<String> firstDieselCar = carsList.stream()
.filter(car -> car.getBrandName().equals("Suziki") && car.getFuelType().equals("D"))
.map(car -> car.getModelName()).findFirst();

System.out.println("First Suziki diesel car name : " + firstDieselCar.get());
}
}

Output:

First Suziki diesel car name : Ciaz

findFirst() method returns Optional instance. Optional.get() method returns the actual value.

We have published already many articles on Optional API.

We can add many conditions as per the requirement. No limitation on this point.

6. Conclusion


In this article, We've seen how to use new Java 8 Stream API filter functionality. Stream API has a filter() method that takes Predicate.

Predicate is a condition that passing to the filter method. The filter() method constructs a new Stream instance which satisfies the predicate.

Shown the examples before java 8 and in Java 8. 

All code shown is over GitHub. Class names are StreamFilterExamples.java and StreamFilterExamplesBeforeJava8.java.
API Ref

No comments:

Post a Comment