Back to articles
Part-4 Functional Interface(Function)

Part-4 Functional Interface(Function)

via Dev.tos mathavi

Function : A functional interface in java.util.function. Represents a transformation: takes an input of type T and produces an output of type R. Core Method: R apply(T t) Extra Methods in Function: Function is more powerful than Consumer because it supports chaining both before and after. 1. andThen(Function after) First applies the current function, then applies the after function on the result. Function<String, Integer> lengthFinder = str -> str.length(); Function<Integer, Integer> square = n -> n * n; Function<String, Integer> lengthSquared = lengthFinder.andThen(square); System.out.println(lengthSquared.apply("Java")); // 16 2. compose(Function before) First applies the before function, then applies the current function. Function<Integer, Integer> square = n -> n * n; Function<Integer, String> toString = n -> "Result: " + n; Function<Integer, String> squareThenString = toString.compose(square); System.out.println(squareThenString.apply(5)); // Result: 25 Example for Compose import

Continue reading on Dev.to

Opens in a new tab

Read Full Article
6 views

Related Articles