The Function Interface is introduced in Java 8, to implement functional programming in Java. It represents a function that takes in one argument and produces a result. It's easy to practise and read, but I am still trying to understand the benefit of it other than just making it look cool. For example,
Function<Integer, Double> half = a -> a / 2.0;
Function<Double, Double> triple = b -> b * 3;
double result = half.andThen(triple).apply(8);
can just be converted as a standard method like
private Double half(int a) {
return a / 2.0;
}
private Double triple (int b) {
return b * 3;
}
double result = triple(half(8));
So what's the benefit of using Function? As it refers to functional programming, what exactly is functional programming in Java and benefit it could bring? Would it benefit the way like:
- execution of chaining functions together (e.g andThen & compose)
- usage inside Java
Stream? - the access modifier as function tends to define with private not public, while method can be either?
Basically, I'm curious to know, in what circumstances would we prefer using function rather than normal method? Is there any use case that's unable or difficult to use, or converted with a normal method?
Comparatorthat would depend on additional input (so sort order would depend dynamically). Using a static method declaration would have required adding a field for the additional input, which would be ugly. Defining aFunctiondynamically solved it.