Java Method References
A method reference names an existing method without calling it. The double colon :: joins the owner to the method name.
System.out::println feeds a forEach
forEach needs an action for each element. The reference hands it the println method directly.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = List.of("Ana", "Ben", "Cy");
names.forEach(System.out::println);
}
}String::toUpperCase as a Function
The reference fits a Function<String, String>. Each incoming string becomes the object toUpperCase runs on.
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<String, String> upper = String::toUpperCase;
System.out.println(upper.apply("stream"));
System.out.println(upper.apply("java"));
}
}A static helper by class name
Shouter::addMark names a static method on the Shouter class. The Function call runs that method.
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<String, String> shout = Shouter::addMark;
System.out.println(shout.apply("Go"));
System.out.println(shout.apply("Done"));
}
}
class Shouter {
static String addMark(String text) {
return text + "!";
}
}Lambda and reference print the same lines
The first loop passes a lambda that prints each word. The second loop passes the reference form of the same rule.
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = List.of("pen", "cup");
words.forEach(word -> System.out.println(word));
words.forEach(System.out::println);
}
}Example
import java.util.List;
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
List<String> cities = List.of("Oslo", "Lima");
Function<String, String> upper = String::toUpperCase;
for (String city : cities) {
System.out.println(upper.apply(city));
}
cities.forEach(System.out::println);
}
}Key points
- A method reference stands where a functional interface is expected.
- System.out::println names the println method of the standard output object.
- String::toUpperCase uses the incoming string as the object the method runs on.
- A static method is referenced with its class name, two colons and the method name.
- A lambda and a method reference can carry the same rule into the same call.
In this example, String::toUpperCase fills a Function that prints each city in capitals. System.out::println then prints the same list in its stored form. The two pairs of lines show one list read by two references.
Note
A constructor reference writes the type name, two colons and new, as in Student::new.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the reference System.out::println name?