Java8 | Function

Hasan Kadir Demircan
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;

FunctionTest01.java
  • 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

FunctionTest02.java

Another example;

FunctionTest03.java
  • 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,

FunctionTest04.java
  • You can use it while you call the method,

Java 8 code example showing usage of Function.andThen() method;

FunctionTest05.java
  • 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

--

--

Hasan Kadir Demircan
Hasan Kadir Demircan

No responses yet