Tuesday, September 2, 2014

Java 8 Functional Interfaces

Java 8 has many functional interfaces as defined in the Javadoc. In this blog, I'm going to explain few important Java 8 functional interfaces.
  • Consumer<T>
    • Arguments: T
    • Returns: Void
  • Supplier<T>
    • Arguments: None
    • Returns: T
  • Function<T, R>
    • Arguments: T
    • Returns: R
  • Predicate<T>
    • Arguments: T
    • Returns: boolean
  • UnaryOperator<T>
    • Arguments: T
    • Returns: T
  • BinaryOperator<T>
    • Arguments: (T, T)
    • Returns: T
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class Java8 {
    public static void main(String[] args) {
        System.out.print("Consumer: ");
        Consumer<String> consumer = (s) -> {
            System.out.println(s);
        };
        consumer.accept("hello");
 
        System.out.print("Supplier: ");
        Supplier<String> supplier = () -> {
            return "foo";
        };
        System.out.println(supplier.get());
         
        System.out.print("Function: ");
        Function<Integer, String> function = (i) -> {
            return "func" + i;
        };
        System.out.println(function.apply(1));
         
        System.out.print("Predicate: ");
        Predicate<Integer> predicate = (i) -> {
            return i == 0;
        };
        System.out.println(predicate.test(0));
         
        System.out.print("UnaryOperator: ");
        UnaryOperator<Integer> unaryOperator = (i) -> {
            return i * 100;
        };
        System.out.println(unaryOperator.apply(2));
         
        System.out.print("BinaryOperator: ");
        BinaryOperator<Integer> binaryOperator = (i, j) -> {
            return i + j;
        };
        System.out.println(binaryOperator.apply(3, 5));
    }
}
Output:
Consumer: hello
Supplier: foo
Function: func1
Predicate: true
UnaryOperator: 200
BinaryOperator: 8