Method References

Method references in Java provide a way to refer to methods or constructors without invoking them. They are often more concise and readable than lambda expressions, especially when the lambda expression merely calls an existing method. Method references are a shorthand notation of lambda expressions.

Static Method References:

Static method references refer to static methods using the syntax ClassName::staticMethodName.

Example:

import java.util.Arrays;
import java.util.List;

public class StaticMethodReferenceExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

        // Using static method reference
        names.forEach(System.out::println);
    }
}

In the above example, System.out::println is a static method reference to the println method of the System class.

Instance Method References:

Instance method references refer to instance methods of a particular object using the syntax object::instanceMethodName.

Example:

import java.util.function.Predicate;

public class InstanceMethodReferenceExample {
    public static void main(String[] args) {
        Predicate<String> isNotEmpty = String::isEmpty;

        System.out.println(isNotEmpty.test("Hello")); // Output: true
        System.out.println(isNotEmpty.test(""));      // Output: false
    }
}

In the above example, String::isEmpty is an instance method reference for the isEmpty method of the String class.

Constructor References:

Constructor references create new objects using constructors. They follow the syntax ClassName::new.

Example:

import java.util.function.Supplier;

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public class ConstructorReferenceExample {
    public static void main(String[] args) {
        Supplier<Person> personSupplier = Person::new;

        Person person = personSupplier.get();
        person.setName("Alice");

        System.out.println(person.getName()); // Output: Alice
    }
}

In the above example, Person::new is a constructor reference that creates new Person objects.

Method references enhance the readability of your code by allowing you to express instances where a lambda expression simply calls an existing method. They provide a clear and concise way to represent functional interfaces, making your code more expressive and easier to understand.

Last updated