Java : Functional interfaces and Lamda expression

I'll show you how you can check a condition and return a boolean value. The java API includes 3 functional interfaces commonly used:
  1. Predicate<T> 
  2. Consumer<T>
  3. Function<T, R>
The Predicate tests the T object and returns a boolean value. The Consumer accepts an operation on T but does not return a value. The Function performs an operation on T and returns an R object.

The static method below uses the Predicate interface to specify the condition:

public static List<Product> filterProducts(List<Product> products,
Predicate<Product> predicate){
List<Product> list = new ArrayList<>();
for(Product p : products){
if(predicate.test(p)){
list.add(p);
}
}
return list;
}


You can use this method like this:

List<Product> productsWithCASNumber = filterProducts(products,
p -> p.getCASNumber() != null);


Thanks

Comments

Popular posts from this blog

Spring JPA : Using Specification with Projection

Chip input using Reactive Form