Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

:: (method reference)

A method reference — an even shorter replacement for a lambda that only calls a method.

Available since: Java 8

Syntax

ClassName::staticMethod
object::method
ClassName::instanceMethod
ClassName::new

Examples

The four kinds of references:

record Point(int x) {}
 
void main() {
    Function<String, Integer> parse = Integer::parseInt;
    Consumer<String> print = IO::println;
    Function<String, String> upper = String::toUpperCase;
    Function<Integer, Point> create = Point::new;
    print.accept("text");
    IO.println(parse.apply("42") + 1);
    IO.println(upper.apply("java"));
    IO.println(create.apply(7));
}

Output:

text
43
JAVA
Point[x=7]

In a stream references read like a list of steps:

void main() {
    List<String> raw = List.of(" 10", "7 ", " 3 ");
    int sum = raw.stream().map(String::trim).mapToInt(Integer::parseInt).sum();
    IO.println(sum);
}

Output:

20

Notes

String::length is the same as s -> s.length(), IO::println as x -> IO.println(x), and ArrayList::new as () -> new ArrayList<>(). If a lambda does anything besides calling one method, keep the lambda.

See also

  • -> (lambda) — A lambda expression — a short function that can be passed around as a value.
  • Function — A function that takes a value of type `T` and returns a value of type `R`.
  • Stream.map() — Transforms every element of a stream.

In the tutorial

  • Method references — Method references in Java: the :: operator, references to static methods, methods of an object, methods of an arbitrary object and constructors.

Thanks for reading!

Donate to the site — we work hard for you.