Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Lambda: Method Reference

DZone's Guide to

Java Lambda: Method Reference

Wanting to learn more about lambda expressions in Java? Check out this post where we look an important feature of Java lambdas — the method reference.

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Java lambda expressions were new in Java 8, profoundly enhancing the expressive power of Java. A Java lambda expression is an anonymous (that is, unnamed) method that can be created without belonging to any class. Instead, it is used to implement a method defined by a function interface (this interface contains one — and only one — abstract method but also can contain multiple default and static methods). Thus, a lambda expression results in a form of anonymous class. 

Method reference is an important feature related to lambda expressions, which can let you reuse existing method definitions and pass them just like lambda expressions. It has the syntax form of:

  Object :: methodName


In a method reference, you place the object (or class) that contains the method that you want to call before the delimiter ::  operator and the name of the method is provided after it without arguments.

There are four types of method references:

Type

Syntax

Lambda

Reference to a static method 

ClassName::staticMethodName

(args) -> ClassName.staticMethodName(args)

Reference to an instance method of an existing object

object::instanceMethodName

(args) -> object.instanceMethodName(args)

Reference to an instance method of an arbitrary object of a particular type

ClassName::instanceMethodName

(arg0,rest) -> arg0.instanceMethodName(rest)

Note: argo is of type ClassName

Reference to a constructor

ClassName::new

(args) -> new ClassName(args)

Each of these types of method references are covered in the following sections.

Static Method Reference

The following program demonstrates the static method reference. First, it declares a functional interface called Intpredicate that has a method called  check(). This method has an int parameter and returns a boolean value. Thus, it can can be used to test an integer value against some conditions. Then, the program creates a class called the IntPredicatesChecker, which defines two staticmethods,  isEven() and  isPositive(). Inside the  StaticMethodReferenceDemo class, a method called numCheck() is defined that has its first parameter, a reference to IntPredicate. Its second parameter specifies the integer being checked. Inside the  main(), two different checks are performed by the call numCheck(), passing in a method reference to the check to perform.

@FunctionalInterface
public interface IntPredicate {
    boolean check(int i);
}

public class IntPredicatesChecker {
    // A static method for checking if  a number is positive
    public static boolean isPositive(int n) {
        return n > 0;
    }

    // A static method for checking if a number is even
    public static boolean isEven(int n) {
        return (n % 2) == 0;
    }
}

public class StaticMethodReferenceDemo {
    public StaticMethodReferenceDemo() {
    }

    // This method takes a functional interface as the type of its first parameter. Thus it can accept a reference to any instance of that
    // interface, including one created by a method reference
    public boolean numCheck(IntPredicate p, int n) {
        return p.check(n);
    }

    public static void main(String[] args) {
        StaticMethodReferenceDemo demo = new StaticMethodReferenceDemo();
        boolean result;
        int num = 9;
        // Here, Using lambda expression to check if a number is even
        IntPredicate lb1 = number -> (number % 2) ==0;
        result = demo.numCheck(lb1, num);
        System.out.println("Using lambda expression: " + num + " is even: " + result);

        // Here, a method reference to  static method isEven of IntPredicatesChecker is passed to numCheck().
        result = demo.numCheck(IntPredicatesChecker::isEven, num);
        System.out.println("Using static method reference: " + num + " is even: " + result);

        // Here, Using lambda expression to check if a number is positive
        IntPredicate lb2 = number -> number > 0;
        result = demo.numCheck(lb2, num);
        System.out.println("Using lambda expression: " + num + " is positive: " + result);

        // Here, a method reference to  static method isPositive of IntPredicatesChecker is passed to numCheck().
        result = demo.numCheck(IntPredicatesChecker::isPositive, num);
        System.out.println("Using static method reference: " + num + " is positive: " + result);

    }
}


The program running output is:

Using lambda expression: 9 is even: false
Using static method reference: 9 is even: false
Using lambda expression: 9 is positive: true
Using static method reference: 9 is positive: true


Inside the program, pay special attention to this line:

result = demo.numCheck(IntPredicatesChecker::isEven, num);


Here, a reference to the staticmethod isEven() is passed as the first argument to the  numCheck().Note that theisEven() method has the same method signature and return type as the check() method of the interface IntPredicate. Therefore, isEven() is compatible with theIntPredicate functional interface.

Method Reference to Instance Methods of an Object

The syntax is similar to the static method reference, except that an object of the class is used instead of a class name. The below program illustrates this point. It uses the same IntPredicate interface in the previous program. And, a class called  IntNumChecker, which has an int instance field and defines the method  isBigger(). This determines if the instance value num of an object is bigger than the value passed in.  

public class IntNumChecker {
    final private int num;

    public IntNumChecker(int num) {
        this.num = num;
    }

    public int getNum() {
        return num;
    }

    // check if num is bigger than the input value n
    boolean isBigger(int n) {
        return num > n;
    }

    public static void main(String[] args) {
        IntNumChecker checker = new IntNumChecker(10);
        int numToCompare = 9;
        IntPredicate p = checker::isBigger;
        boolean result = p.check(numToCompare);
        if (result) {
            System.out.println(checker.num + " is bigger than " + numToCompare);
        }else {
            System.out.println(checker.num + " is smaller or equal than " + numToCompare);
        }
    }
}


The output of the program is:

10 is bigger than 9


You need to  pay special attention to this line:

IntPredicate p = checker::isBigger;

The method reference assigned to p refers to an instance method isBigger() on object checker  of IntNumChecker. Thus, when check() is called through that reference p, as shown here:

result = p.check(9);


This method, check(), will call isBigger() in the object checker.

Parameter Method Reference

This type is the most abstract one between all these four types. In this case, instead of using a specific object, you can use the name of the class. Therefore, the first parameter of the functional interface matches the invoking object. This is why we call it the parameter method reference. Rest parameters match the parameters (if any) that are specified by the method. The following example reimplements the previous example by using the parameter method reference. First, we will look at a functional interface, IntNumPredicatewith a single abstract method called  check(). The check()'s first parameter is of the typeIntNumChecker that will be used to accept the object being operated upon, and the second parameter takes an int value.  This allows us to create a method reference to the instance methodisBigger() that can be used with any IntNumChecker  objects (e.g checker 1 and check 2).

@FunctionalInterface
public interface IntNumPredicate {
    boolean check(IntNumChecker m, int n);
}

public class IntNumChecker {
    final private int num;

    public IntNumChecker(int num) {
        this.num = num;
    }

    // check if num is bigger than the input value n
    boolean isBigger(int n) {
        return num > n;
    }

    public static void main(String[] args) {
        IntNumChecker checker1 = new IntNumChecker(10);
        int numToCompare = 9;
        IntNumPredicate p = IntNumChecker::isBigger;
        boolean result = p.check(checker1,9);
        if (result) {
            System.out.println(checker1.num + " is bigger than " + numToCompare);
        }else {
            System.out.println(checker1.num + " is smaller  " + numToCompare);
        }

        // second object of IntNumChecker
        IntNumChecker checker2 = new IntNumChecker(8);
        result = p.check(checker2,9);

        if (result) {
            System.out.println(checker2.num + " is bigger than " + numToCompare);
        }else {
            System.out.println(checker2.num + " is smaller " + numToCompare);
        }
    }
}


You need to pay special attention to this line:

 IntNumPredicate p = IntNumChecker::isBigger;


The method reference assigned to p refers to the method  isBigger() on any object (e.g. checker1, checker2) of the IntNumChecker

Reference to a Constructor

Constructor references work similarly to a reference to a static method. In the demonstrated program, we created two functional interfaces to show how to use the constructor reference. In the interface  IntSupplier, the apply() method accepts an int value and returns an ObjIntCreation object, while in the interface IntObjectSupplier, the  apply() method accepts an object ofObjIntCreation and returns an ObjIntCreation object. In the  main(), it demonstrates two examples of creating objects using constructor reference. In the first example, the apply(num) method matches the apply() method in the interface IntSupplier, while in the second example, the apply(newObj1) method, matches theapply()method in the interface IntObjectSupplier.

@FunctionalInterface
public interface IntSupplier {
    ObjIntCreation apply(int n);
}

@FunctionalInterface
public interface IntObjectSupplier {
    ObjIntCreation apply(ObjIntCreation obj);
}

public class ObjIntCreation {
    private int num;

    public ObjIntCreation(int num) {
        this.num = num;
    }

    public ObjIntCreation(ObjIntCreation n) {
        this.num = n.num;
    }

    public static void main(String[] args) {

        // using the "IntSupplier" functional interface
        int num = 10;
        IntSupplier s1 = ObjIntCreation::new;
        ObjIntCreation newObj1 = s1.apply(num);
        System.out.println("new object has a instance value " + newObj1.num);

        // using the "IntObjectSupplier" functional interface
        IntObjectSupplier s2 = ObjIntCreation::new;
        ObjIntCreation newObj = s2.apply(newObj1);
        System.out.println("new object has a instance value " + newObj.num);
    }
}


Conclusion

In conclusion, method references can be used to make your code more concise and readable. For example, you can avoid the one method restriction by putting all your code in a static method and create a reference to that method instead of using a class or a lambda expression with many lines. Hope this helps. Let us know what you think in the comments below!

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:
java ,method references ,lambda expressions ,functional interface ,parameter ,java 8 ,static method ,static

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}