Questions tagged [method-reference]

Method references, introduced in Java 8, are a way to refer to a method by its name instead of using a lambda expression.

Method references were introduced in alongside lambda expressions.

The programmer can use a method reference as a syntactic sugar for a lambda expression that would merely call that method, when its signature is compatible with the type.

The syntax of a method reference closely matches a method invocation expression, but with a double colon (::) replacing the dot (.).

// static method reference:
ToIntFunction<String> parseInt = Integer::parseInt;
int i = parseInt.applyAsInt("123");

// instance method reference:
Consumer<Object> println = System.out::println;
println.accept("Hello world!");

// constructor method reference:
Supplier<Object> newObject = Object::new;
Object o = newObject.get();

// array creation method reference:
IntFunction<Number[]> newArray = Number[]::new;
Number[] a = newArray.apply(10);

When working with generics, type arguments may be provided explicitly or inferred.

Supplier<List<String>> listSupplier;

// explicit type argument for a class:
listSupplier = ArrayList<String>::new;
// inferred type argument for a class:
listSupplier = LinkedList::new;
//             ^^^^^^^^^^
//             note: not a raw type in this context!
//             LinkedList<String> will be inferred.

// explicit type argument for a method:
listSupplier = Collections::<String>emptyList;
// inferred type argument for a method:
listSupplier = Collections::emptyList;

See also:

567 questions
1129
votes
17 answers

:: (double colon) operator in Java 8

I was exploring the Java 8 source and found this particular part of code very surprising: // Defined in IntPipeline.java @Override public final OptionalInt reduce(IntBinaryOperator op) { return…
Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
397
votes
18 answers

Java Pass Method as Parameter

I am looking for a way to pass a method by reference. I understand that Java does not pass methods as parameters, however, I would like to get an alternative. I've been told interfaces are the alternative to passing methods as parameters but I…
Mac
149
votes
4 answers

Comparator.reversed() does not compile using lambda

I have a list with some User objects and i'm trying to sort the list, but only works using method reference, with lambda expression the compiler gives an error: List userList = Arrays.asList(u1, u2, u3); userList.sort(Comparator.comparing(u ->…
Andrey
  • 2,485
  • 3
  • 21
  • 26
111
votes
2 answers

Horrendous performance & large heap footprint of Java 8 constructor reference?

I just had a rather unpleasant experience in our production environment, causing OutOfMemoryErrors: heapspace.. I traced the issue to my use of ArrayList::new in a function. To verify that this is actually performing worse than normal creation via a…
Anders K
  • 1,129
  • 2
  • 8
  • 12
86
votes
3 answers

Is method reference caching a good idea in Java 8?

Consider I have code like the following: class Foo { Y func(X x) {...} void doSomethingWithAFunc(Function f){...} void hotFunction(){ doSomethingWithAFunc(this::func); } } Suppose that hotFunction is called very often.…
gexicide
  • 38,535
  • 21
  • 92
  • 152
74
votes
2 answers

Java 8 pass method as parameter

Currently getting into Java 8 lambda expressions and method references. I want to pass a method with no args and no return value as argument to another method. This is how I am doing it: public void one() { System.out.println("one()"); } public…
Torsten Römer
  • 3,834
  • 4
  • 40
  • 53
59
votes
2 answers

java.lang.NullPointerException is thrown using a method-reference but not a lambda expression

I've noticed something weird about unhandled exceptions using Java 8 method reference. This is my code, using the lambda expression () -> s.toLowerCase(): public class Test { public static void main(String[] args) { testNPE(null); …
59
votes
1 answer

How do Java 8 array constructor references work?

Say we have a variable of type IntFunction that returns an integer array: IntFunction i; With Java 8 generics, it is possible to initialize this variable with a constructor reference like this: i = int[]::new How does the Java compiler…
Clashsoft
  • 11,553
  • 5
  • 40
  • 79
55
votes
1 answer

New object instantiation when using Java 8 streams

Is there a differnce in using the following contstructs, other than slightly better readability in the latter? someList.stream().map(item -> new…
ShellDragon
  • 1,712
  • 2
  • 12
  • 24
51
votes
1 answer

Use method reference with parameter

I just started learning Java streams and faced a problem. Please take a look at a the following example. This is part of a Node class: private Map nodes; public Optional child(String name) { return…
46
votes
2 answers

Static context cannot access non-static in Collectors

I have group of students. First I want to group them by the marks. Then I want to further group those sets into same name students together. Map>> groupping = students.stream() …
Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62
38
votes
4 answers

Why is lambda return type not checked at compile time?

The used method reference has return type Integer. But an incompatible String is allowed in the following example. How to fix the method with declaration to get the method reference type safe without manually casting? import…
jukzi
  • 984
  • 5
  • 14
37
votes
7 answers

Java8 method reference used as Function object to combine functions

Is there a way in Java8 to use a method reference as a Function object to use its methods, something like: Stream.of("ciao", "hola", "hello") .map(String::length.andThen(n -> n * 2)) This question is not related to the Stream, it is used just…
rascio
  • 8,968
  • 19
  • 68
  • 108
35
votes
4 answers

Why can method reference use non-final variables?

I had some confusion about inner classes and lambda expression, and I tried to ask a question about that, but then another doubt arose, and It's probable better posting another question than commenting the previous one. Straight to the point: I know…
Luigi Cortese
  • 10,841
  • 6
  • 37
  • 48
34
votes
1 answer

Java 8 chained method reference?

Suppose there is a typical Java Bean: class MyBean { void setA(String id) { } void setB(String id) { } List getList() { } } And I would like to create a more abstract way of calling the setters with the help of a…
Random42
  • 8,989
  • 6
  • 55
  • 86
1
2 3
37 38