Java 8 : Function

What is a Function?

This is a predefined functional interface like Predicatepresent in java.util.function package. It has one abstract method called apply();


1
2
3
interface Function<T,R> {
public R apply(T t);
}


Function example 1: to check the length of the string.

 1
2
3
4
5
6
7
8
9
10
11
12
package com.blogspot.ekumeedkiasha;

import java.util.function.Function;

public class FunctionExample1 {

public static void main(String[] args) {
Function<String, Integer> fun = s -> s.length();
System.out.println(fun.apply("ekumeedhelp"));
}

}

Function Chaining example:
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.blogspot.ekumeedkiasha;

import java.util.function.Function;

public class FunctionChaining {

public static void main(String[] args) {

int amount = 3;

Function<Integer, Integer> sum = i -> i + i; // 3 + 3 = 6

Function<Integer, Integer> sq = i -> i * i; // 6 * 6 = 36

System.out.println(sum.apply(amount));

System.out.println(sq.apply(amount));

System.out.println(sum.andThen(sq).apply(amount));

System.out.println(sum.compose(sq).apply(amount));

}

}

 

Share this

Related Posts

Previous
Next Post »