How to Filter values using Java 8



Filtering data is the common functionality used in many applications. When you're bringing more data from the database, You may need to filter out based on certain conditions and then present to end user in UI.

Example: We are working on a Cars Dealer application. There is a functionality we have to filter cars based on brand.

There is a Car class with a property name brand.we have to filter our cars from the collection of cars.
In java8 introduced the concept of streams.it became more simple than an older version of java.

First, we will see how to filter from the list of strings.

Example: we have a list of names. Filter names start with letter 'k', collect all filtered values into another list.

  
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class FilterDemo {
public static void main(String args[]) {

List<String> names = new ArrayList<>();
names.add("amar");
names.add("kiran");
names.add("Raja");
names.add("Krishna");
names.add("rahul");
names.add("kishore");

List<String> filteredNames = names.stream().filter(name -> name.startsWith("k")).collect(Collectors.toList());

for (String name : filteredNames) {

System.out.println(name);
}

}

}

In the above example, we are iterating through a list of strings using streams. 
using a filter method to filter values based on a condition. 

finally using collect method and Collectors.toList() method to collect filtered values into a list. 
Now we will see how to use a filter with our own class. Let's take an example we have a collection of cars. Filter cars based on brand ford using java 8 streams.

  import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class CarFilterDemo {
public static void main(String args[]) {
List<Car> cars= new ArrayList<>();
cars.add(new Car("Red","Hatchbag","Ford"));
cars.add(new Car("green","Hatchbag","Maruthi"));
cars.add(new Car("Red","Sedaan","BMW"));
cars.add(new Car("Red","SUV","Ford"));
//filter cars with brand - Ford
List<Car> filtercars = cars.stream().
filter(car -> car.getBrand().equalsIgnoreCase("Ford")).
collect(Collectors.toList());
// print all filtered cars
for(Car car : filtercars) {
System.out.println("Car brand "+car.getBrand());
}
}

}

In the above example, we are iterating through list of cars and calling a filter method to filter based on the car brand. 

Inside the filter, we are using a condition to check car brand is ford or not. 
if it is ford that object will be given to the next adjacent method.
If you observe here methods are connected through dots.we can call this as a pipeline. 
filtered objects are getting collected at the collect method. 

Collected objects we are converting into a list of cars using Collectors.toList() method. 
With a single line of code, we can easily filter values with streams in java 8. Use Streams and make it simple.

Comments

Post a Comment