Unbound Instance Method Reference

Description

An unbound receiver uses the following syntax

ClassName::instanceMethod

It is the same syntax we use to reference a static method.

From the following code we can see that the input type is the type of ClassName.

In the following code we use String:length so the functional interface input type is String.

The lambda expression gets the input when it is being used.

Example

The following code uses the String length method as unbind instance method reference.

The String length method is usually called on a string value instance and returns the length of the string instance. Therefore the input is the String type and output is the int type, which is matching the buildin Function functional interface.

Each time we call strLengthFunc we pass in a string value and the length method is called from the passed in string value.


import java.util.function.Function;
/*from w  w  w .j a v a 2  s. com*/
public class Main{
  public static void main(String[] argv){
    Function<String,  Integer> strLengthFunc = String::length; 
    String name ="java2s.com";
    int len   =  strLengthFunc.apply(name); 
    System.out.println("name  = "  +  name + ", length = "  + len);
    
    name ="www.java2s.com";
    len   =  strLengthFunc.apply(name); 
    System.out.println("name  = "  +  name + ", length = "  + len);

  }
}

The code above generates the following result.

Example 2

The following code defines a class Util with a static method called append.

The append method accepts two String type parameters and returns a String type result.

Then the append method is used to create a lambda expression and assigned to Java buildin BiFunction functional interface.

The signature of append method matches the signature of the abstract method defined in BiFunction functional interface.


import java.util.function.BiFunction;
/*from  w  w  w.  j  a va2 s. c o  m*/
public class Main{
  public static void main(String[] argv){
    BiFunction<String,  String,String> strFunc = Util::append; 
    String name ="java2s.com";
    String s=  strFunc.apply(name,"hi"); 
    System.out.println(s);
  }
}
class Util{
  public static String append(String s1,String s2){
    return s1+s2;
  }  
}

The code above generates the following result.





















Home »
  Java Lambda »
    Java Lambda Tutorial »




Java Lambda Tutorial