Skip to content

Streams

Thomas Czogalik edited this page Sep 10, 2018 · 1 revision

Summary of the book "Modern Java Recipes" by Ken Kousen [1]

Method References

  • treat a method like a lambda expression
  • use :: to separate class name from method
  • context provides arguments or target

object::instanceMethod

Refer to an instance method using a reference to supplied object, as in System.out::println

x -> System.out.println(x)

Class::staticMethod

Refer to static method, as in Math::max

(x, y) -> Math.max(x, y)

Class::instanceMethod

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

Constructor Reference

Person::new

Copy Constructor breaks connection between before and after reference

after = Stream.of(before)
   .map(Person::new)
   .collect(Collectors.toList())

Functional Interfaces

  • Interface with single abstract method
  • @FunctionalInterface Annotation
  • 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()

References

[1] "Modern Java Recipes" by Ken Kousen, http://shop.oreilly.com/product/0636920056669.do

Clone this wiki locally