identity() and other default methods

Functional interfaces of the java.util.function package have other helpful default methods. The one that stands out is the identity() method, which returns a function that always returns its input argument:

Function<Integer, Integer> id = Function.identity();
System.out.println(id.apply(4)); //prints: 4

The identity() method is very helpful when some procedure requires providing a certain function, but you do not want the provided function to change anything. In such cases, you create an identity function with the necessary output type. For example, in one of our previous code snippets, we may decide that the multiplyByFive function should not change anything in the multiplyByFive.andThen(subtract7) chain:

Function<Double, Double> multiplyByFive = Function.identity();
System.out.println(multiplyByFive.apply(2.)); //prints: 2.0

Function<Double, Long> subtract7 = createSubtractInt(7);
System.out.println(subtract7.apply(11.0)); //prints: 4

long r = multiplyByFive.andThen(subtract7).apply(2.);
System.out.println(r); //prints: -5

As you can see, the  multiplyByFive function did not do anything with the input parameter 2, so the result (after 7 was subtracted) is -5.

Other default methods are mostly related to conversion and boxing and unboxing, but also extracting minimum and maximum values of two parameters. If you are interested, you can look through the API of interfaces of the java.util.function package and get a feeling for the possibilities.