Java Reference
In-Depth Information
else {
return n * factorial(n - 1);
}
}
}
factorial of 5 is 120
You can achieve the same results using an anonymous inner class as shown:
IntFunction<Long> factorialCalc = new IntFunction<Long>() {
@Override
public Long apply(int n) {
if (n < 0) {
String msg = "Number must not be negative.";
throw new IllegalArgumentException(msg);
}
if (n == 0) {
return 1L;
}
else {
return n * this.apply(n - 1);
}
}
};
Comparing Objects
The Comparator interface is a functional interface with the following declaration:
package java.util;
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
/* Other methods are not shown. */
}
The Comparator interface contains many default and static methods that can be used along with lambda
expressions to create its instances. It is worth exploring the API documentation for the interface. In this section, I will
discuss the following two methods of the Comparator interface:
static <T,U extends Comparable<? super U>>Comparator<T>
comparing(Function<? super T,? extends U> keyExtractor)
default <U extends Comparable<? super U>>Comparator<T>
thenComparing(Function<? super T,? extends U> keyExtractor)
 
Search WWH ::




Custom Search