What is new in Java 8 (LTS)
Release date 18th March 2014.
1. Functional Interface
Java 8 introduced @FunctionalInterface, an interface that has exactly one abstract method. The compiler will treat any interfaces meeting the definition of a functional interface as a functional interface; it means the @FunctionalInterface annotation is optional.
Let us see the six basic function interfaces.
| Interface | Signature | Examples |
|---|---|---|
| UnaryOperator<T> | T apply(T t) | String::toLowerCase, Math::tan |
| BinaryOperator<T> | T apply(T t1, T t2) | BigInteger::add, Math::pow |
| Function<T, R> | R apply(T t) | Arrays::asList, Integer::toBinaryString |
| Predicate<T, U> | boolean test(T t, U u) | String::isEmpty, Character::isDigit |
| Supplier<T> | T get() | LocalDate::now, Instant::now |
| Consumer<T> | void accept(T t) | System.out::println, Error::printStackTrace |
2. Lambda Expressions & Method References
Java 8 introduced lambda expressions to provide the implementation of the abstract method of a functional interface.
Review the JDK Iterable class, it has a default method forEach() to accept a function interface Consumer
public interface Iterable<T> {
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
//...
}
First, we can provide an anonymous class as the forEach implementation.
List<String> list = Arrays.asList("node", "java", "python", "ruby");
list.forEach(new Consumer<String>() { // anonymous class
@Override
public void accept(String str) {
System.out.println(str);
}
});
Alternatively, we can use a lambda expression to shorten the code like this:
List<String> list = Arrays.asList("node", "java", "python", "ruby");
list.forEach(str -> System.out.println(str)); // lambda expressions
To gain better readability, we can replace lambda expression with method reference.
List<String> list = Arrays.asList("node", "java", "python", "ruby");
list.forEach(System.out::println); // method references
Both lambda expression or method reference does nothing but just another way call to an existing method. With method reference, it gains better readability.