Reference To An Instance method Of a Class (Method References)
In this lesson, you will learn about the third kind of method reference, "a reference to an instance method of an arbitrary object of a particular type". You will be introduced to a couple of simple examples and detailed explanations to understand this topic.
Table of Contents
What is a reference to an instance method of a class?
This type is also called "a reference to an instance method of an arbitrary object of a particular type."
This method reference refers to an instance method of an object of a particular type determined at runtime.
Syntax
ClassName::instanceMethodName
Examples
Some examples will help you understand this kind of method reference.
A) List of strings
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ListOfObjects {
public static void main(String[] args) {
List<Person> people =
Arrays.asList(
new Person("Alice"),
new Person("Bob"),
new Person("Charlie")
);
List<String> names =
people
.stream()
.map(Person::getName)
.collect(Collectors.toList());
System.out.println(names);
}
}
Person
class contains a single instance variable and a method getName
that returns the name.
On line 7 of Example
class, we created a collection of items and added few Person
objects.
On line 15, we have a list of persons chained with the .stream()
method on line 16th.
On line 17, we get the list of person names and collect them to a list of strings on line 20.
Similarly, the method reference String::concat
would invoke the method a.concat(b)
B) Sorting integers
This is a classic sorting example where we make use of compareTo
method in Integer
class.
import java.util.Arrays;
import java.util.List;
public class SortingIntegers {
public static void main(String[] args) {
List<Integer> integerValues = Arrays.asList(11, 4, 2, 8, 9, 10, 32, 22, 20, 17);
integerValues // list of integers
.stream() // stream of integers
.sorted(Integer::compareTo) // method reference
.forEach(System.out::println); // print on console
}
}
On line 6, we have a list of integer items randomly stored.
On line 9, we chained it with .stream()
to convert the list of integer values into a stream of integer values.
Line 10 contains an intermediate operation .sorted
that takes Integer::compareTo
that sorts the integer values.
Line 11 prints each of the integer on the console.
Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.