Bound Instance Method Reference

Description

Bound Receiver receiver has the following form:

instance::MethodName

In their following code we use the buildin system functional interface Supplier as the lambda expression type.

At first we define a lambda expression in a normal way. The lambda expression accepts no parameter and returns the length of a string 'java2s.com'

Then we create a String instance with 'java2s.com' and use its length method as the instance method reference.

Bound means we already specify the instance.

Example 1

The following example shows how to use bound receiver and method with no parameters to create Instance Method References.


import java.util.function.Supplier;
/*from   w  ww.j a  va 2  s  .c  o m*/
public class Main{
  public static void main(String[] argv){
    Supplier<Integer> supplier  = () ->  "java2s.com".length(); 
    System.out.println(supplier.get());
    
    
    Supplier<Integer> supplier1  = "java2s.com"::length; 
    System.out.println(supplier1.get());
  }
}

The code above generates the following result.

Example 2

The following example shows how to use bound receiver and method with parameters to create Instance Method References.


import java.util.function.Consumer;
/*ww w .  ja va  2s  . c  om*/
public class Main{
  public static void main(String[] argv){
    Util util = new Util();
    
    Consumer<String> consumer  = str ->  util.print(str);
    consumer.accept("Hello"); 
    

    Consumer<String> consumer1  = util::print;
    consumer1.accept("java2s.com");
    
    util.debug();
  }
}
class Util{
  private int count=0;
  public void print(String s){
    System.out.println(s);
    count++;
  }
  public void debug(){
    System.out.println("count:" + count);
  }
}

The code above generates the following result.





















Home »
  Java Lambda »
    Java Lambda Tutorial »




Java Lambda Tutorial