Java8 | Function
2 min readDec 19, 2020
What we need to know about Function
- Function is in the package java.util.function
- Function interface is -> public interface Function<T, R>
- It is combined with the map method found in the stream,
The map () function is a method in the Stream class that represents a functional programming concept. In simple words, the map () is used to transform one object into another by applying a function.
For example, by using the map () function, you can convert a list of String into a List of Integer by applying the Integer.valueOf () method to each String on the input list. - Function methods are below,
R apply(T t);
<V> Function<V, R> compose(Function<? super V, ? extends T> before)
<V> Function<T, V> andThen(Function<? super R, ? extends V> after)
<T> Function<T, T> identity() - We will investigate these methods,
Java 8 code example showing usage of Function.apply() method;
- We define Function in 9. and 10. lines,
- We call apply() method in 13,14,15. lines and then we see results,
Another example below
Another example;
- We define Function<Employee, String> , Its means we give Employee and it returns String
- e-> e.getName() . It takes as input an Employee object and returns his\her name, which is a String value, as output.
Another example,
- You can use it while you call the method,
Java 8 code example showing usage of Function.andThen() method;
- We defined 2 functions 3,4. lines.
- İf you use compose, you should be careful because compose firstly start within and then makes outside.
- We can combine 2 functions like 6. line
Github: Function