-
Notifications
You must be signed in to change notification settings - Fork 0
Streams
Thomas Czogalik edited this page Sep 10, 2018
·
1 revision
Summary of the book "Modern Java Recipes" by Ken Kousen [1]
- treat a method like a lambda expression
- use
::to separate class name from method - context provides arguments or target
Refer to an instance method using a reference to supplied object, as in System.out::println
x -> System.out.println(x)
Refer to static method, as in Math::max
(x, y) -> Math.max(x, y)
Invoke instance method on object supplied by context, as in String::length
x -> x.length()
If multiple arguments are provided, the first becomes the target
(s1, s2) -> s1.compareTo(s2)
//equivalent to
String::compareTo
Person::new
Copy Constructor breaks connection between before and after reference
after = Stream.of(before)
.map(Person::new)
.collect(Collectors.toList())
- Interface with single abstract method
-
@FunctionalInterfaceAnnotation - can have default and static methods
@FunctionalInterface
public interface MyInterface {
int myMethod();
default String sayHello() {...}
static void staticMethod() {...}
}
- can be target for lambda expression or method reference
var myInterface = new MyInterface(() -> System.out.println("MyMethod implementation"))
myInterface.myMethod()
myInterface.sayHello()
MyInterface.staticMethod()
[1] "Modern Java Recipes" by Ken Kousen, http://shop.oreilly.com/product/0636920056669.do