In this post, we will learn about java8 method reference operator in Java
Method Reference (:: Operator)
- “::” operator in Java 8 is known as the Method Reference operator
- Method reference allows you to refer to an existing method by name, instead of invoking it directly
- Method references used in combination with functional interfaces, which are interfaces with a single abstract method, and provide a target type for the method reference.
Method references come in four forms:
- Reference to a static method: ClassName::methodName
- Reference to an instance method of a particular object: objectName::methodName
- Reference to an instance method of an arbitrary object of a particular type: ClassName::methodName
- Reference to a constructor: ClassName::new
For example, consider the following code:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.forEach(System.out::println);
In this case, System.out::println
is a method reference to the println
method of the System.out
object, which is a PrintStream
.
Reference to a static method Example
List<String> words = Arrays.asList("apple", "banana", "cherry");
words.sort(String::compareToIgnoreCase);
Here, String::compareToIgnoreCase
is a method reference to the static method compareToIgnoreCase
of the String
class, which compares two strings ignoring case considerations.
Reference to an instance method of a particular object:
LocalDateTime now = LocalDateTime.now();
List<LocalDateTime> dates = Arrays.asList(
now.minusDays(2),
now.minusDays(1),
now
);
dates.sort(now::compareTo);
Here, now::compareTo
is a method reference to the instance method compareTo
of the LocalDateTime
object now
, which compares two LocalDateTime
instances.
Reference to an instance method of an arbitrary object of a particular type:
List<Employee> employees = getEmployees();
employees.sort(Employee::compareByName);
Here, Employee::compareByName
is a method reference to the instance method compareByName
of the Employee
class, which compares two Employee
objects based on their name.
Reference to a constructor:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Double> squareRoots = numbers.stream()
.map(Math::sqrt)
.collect(Collectors.toList());
Here, Math::sqrt
is a method reference to the static method sqrt
of the Math
class, which returns the square root of a given number.
Thanks for Reading.