Java: Lambda Cheat Sheet
Lambdas
() -> "Hello"
() -> System.out.println("Hello")
(String str) -> str.length()
(str) -> str.length()
str -> str.length()
(int i, int j) -> i + j
(i, j) -> i + j
() -> {
System.out.println("Hello");
System.out.println("World");
}
(int i) -> {
System.out.println("Hello");
return i;
}
Method References
// Static methods
Supplier<Thread> runtimeSup = Thread::currentThread;
// Bound instance methods
Supplier<String> helloSup = "hello"::toUpperCase;
Consumer<String> printer = System.out::println;
// Unbound instance methods
Function<String, String> lower = String::toLowerCase;
// Constructors
Supplier<String> stringSup = String::new;
Function<Integer, int[]> arrSup = int[]::new;
Standard Functional Interfaces
Custom Functional Interfaces
Declared like:
@FunctionalInterface
interface MyInterface {
String method(String str);
}
Used like:
MyInterface doubler = str -> str + str;
String abab = doubler.method("ab");
- Functional interface: Any interface with a single abstract method
- Can have additional
default
methods - The
@FunctionalInterface
annotation (which is optional) causes the compiler to complain if the interface is not a functional interface
Comments
Be the first to comment!