Wednesday, November 29, 2017

Adam Bien on Lambda and Runnable


Java 8 Basics: Method References from AdamBien on Vimeo.



This is my code:




public class TestRun {
 public static void main(String[] args) {
  TestRun testRun = new TestRun();
  testRun.method1();
  testRun.method2();
  testRun.method3();
  testRun.method4();
 }

 
 /**
  * Old Java school
  */
 public void method1() {
  Runnable runnable = new Runnable() {
   @Override
   public void run() {
    System.out.println("ciao1");

   }
  };
  new Thread(runnable).start();
 }

 /**
  * Runnable's only method has no input parameters and only 1 method, 
  * it's a Functional Interface https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html 
  * so we provide method implementation inline (lambda)
  */
 public void method2() {
  Runnable runnable = () -> {
   System.out.println("ciao2");
  };
  new Thread(runnable).start();
 }
 
 /**
  * Syntactic sugar, since there is no parameter we omit the () notation altogether
  */
 public void method3() {
  Runnable runnable = () -> System.out.println("ciao3");
  new Thread(runnable).start();
 }
 
 /**
  * We provide the method (lambda) as a reference
  */
 
 public void method4() {
  Runnable runnable = this::display;
  new Thread(runnable).start();
 }
 
 
 public void display() {
  System.out.println("ciao4");
 }
}



No comments: