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>
- Predicate<T>
- Arguments: T
- Returns: boolean
- UnaryOperator<T>
- BinaryOperator<T>
- Arguments: (T, T)
- Returns: T
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
No comments:
Post a Comment