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:
- Predicate<T>
- Consumer<T>
- Function<T, R>
The
The static method below uses the
You can use this method like this:
Thanks
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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List<Product> productsWithCASNumber = filterProducts(products, | |
p -> p.getCASNumber() != null); |
Thanks
Comments
Post a Comment