Thursday, September 11, 2014

Java 8 : Method References

This is a new concept introduced with Java 8. We refer method reference with “::” (i.e. double colon) operator. This will used to replace lamba expressions like in below code.

import java.util.ArrayList;
import java.util.List;

public class MethodReference {
       public static void main(String[] args) {
              List numbers = new ArrayList<>();
              numbers.add(7);
              numbers.add(4);
              numbers.add(1);
              numbers.add(8);
              numbers.add(5);
              numbers.add(2);
              numbers.add(9);
              numbers.add(6);
              numbers.add(3);
              numbers.add(0);
              //numbers.sort((a,b)->Integer.compare(a,b));
              numbers.sort(Integer::compare);
//numbers.forEach(number -> System.out.println(number));
              numbers.forEach(System.out::println);;
       }
}

This helps you to call in following instances:

 object :: instanceMethod
·         Class :: staticMethod
·         Class :: instanceMethod

And it is also valid to use ‘super’ or ‘this’ with method reference.

public class Greeter {
       public void greet(){
              System.out.println("Hello World!");
       }
}

public class ConcurrenceGreeter extends Greeter {

       @Override
       public void greet() {
              Thread greet = new Thread(super::greet);
              greet.start();
              Thread bye = new Thread(this::bye);
              bye.start();
       }
      
       public void bye(){
              System.out.println("See you again.");
       }

       public static void main(String[] args) {
              Greeter greeter = new ConcurrenceGreeter();
              greeter.greet();
       }

}

No comments:

Post a Comment