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
0
votes
1 answer

Get method object with method references

Is it possible to get an instance of java.lang.reflect.Method by using the new method reference feature of Java 8? That way I would have a compile time check and refactoring would be also easier. Also, I wouldn't need to catch the exceptions (which…
Jimmy T.
  • 4,033
  • 2
  • 22
  • 38
0
votes
2 answers

Simplify field access. Should I use reflection or is there a Java 8 solution?

I've got the following example class: public class MyPermission implements Permission { public static final String READ = "read"; public static final String UPDATE = "update"; public static final String DELETE = "delete"; @Override …
Benjamin M
  • 23,599
  • 32
  • 121
  • 201
-1
votes
1 answer

Why i cant use StringBuilder::reverse in as method reference to reverse a string?

Why i cant use StringBuilder::reverse in as method reference to reverse a string? please help make me understand whats going on under the hood. import java.util.ArrayList; import java.util.Arrays; import java.util.List; import…
LakshayGMZ
  • 51
  • 5
-1
votes
2 answers

List of non-static method references in Java

I am trying to use a list of function references as a lookup table (avoiding the need for a long switch statement). The code worked for a list of static methods, but when I tried to use non-static (i.e. instance) methods in the list, Java gives…
ThePythonator
  • 154
  • 2
  • 13
-1
votes
1 answer

How Inheritance works in Java with method reference operator

Interface public interface InterfaceOne { void start(); void stop(); } Main Class public class MainProg { public static void main(String [] args){ new ServiceA().start(); } } ServiceA import java.util.ArrayList; import…
Programming-Lover
  • 1,177
  • 10
  • 14
-1
votes
2 answers

Why and When should I use Functional Interfaces

Say I am writing a Consumer which prints something on the console. Then why shouldn't I directly use the System.out.println() method instead of creating a Consumer? Similarly, say I want to return a random number, then we can use Random object…
Ashish Singh
  • 399
  • 4
  • 11
-1
votes
1 answer

Calling method reference using lambda (:: operator)

I have seen some approaches as shown below: calling like this: private static void addCustomerTransaction() { customerInput((bank, branchName, customerName, transaction) -> bank.addCustomerTransaction(branchName, customerName,…
user17188729
-1
votes
2 answers

Method references not working in Java stream filter

I have a list with some strings and I want to filter these list, but the methode reference ::startsWith is not working as I expect it. private static final String KEY = "key="; List keyList = List.of("key=123", "value12", "value=34",…
Mani76
  • 357
  • 1
  • 3
  • 14
-1
votes
1 answer

Comparator.comparing() function returns different results with lambdas and method reference

I am trying to sort an Array of Strings based on their lengths using Comparator.comparing function. So, I have the following piece of code: String[] arr = new String[]{"Hello","I","Am","Learning","Java"}; When I try to sort it in decreasing order…
Mehul
  • 47
  • 5
-1
votes
2 answers

Java 8 - Object method reference executes method of null reference

Please see my code below. I have a functional interface IFace with a method. I'm creating an implementation using Method reference from a class instance of Test. Can anyone tell me how the interface still refers to the instance method even if the…
Coder
  • 54
  • 6
-1
votes
2 answers

What is the difference between Collections.emptyList() vs Collections::emptyList

When using java stream show error while coding Optional.ofNullable(product.getStudents()) .orElseGet(Collections.emptyList()) .stream().map(x->x.getId) .collect(Collectors.toList()); this code shows…
Araf
  • 510
  • 8
  • 32
-1
votes
2 answers

Using double colon for object referenced method Java 8

I have 2 List and need to intersection them by xxx.getId(), so I use Stream and Lambda. These steps are: List list1 = function1(); List list2 = function2(); List list1InString = list1.stream().map(input ->…
mmo2112
  • 15
  • 8
-1
votes
3 answers

Is there any difference between “invoking a static method with Classname.staticMethod” & “invoking with Classname::staticMethod” in java8

Is there any difference between “invoking a static method with Classname.staticMethod” and “invoking a static method with Classname::staticMethod” in java? Also is there a difference between “invoking a method with Object.method” and “invoking a…
Thiagarajan Ramanathan
  • 1,035
  • 5
  • 24
  • 32
-1
votes
1 answer

Conversion of Lambda expression to Method reference

I was trying to convert a lambda expression into method reference, but I failed to do so. can anybody help me with this? The lambda expression takes 2 int parameters adds it and return the result. public class Addition { public static void…
Ashish Singh
  • 399
  • 4
  • 11
-1
votes
1 answer

What is the best way to design/process in Java 8 ordered calls on different methods

My question is regarding design I'm trying to design order/sequential calls based on different methods. Suppose my Class : public class Foo { public Object method1(String a){ // impl1.. } public Object method2(List
VitalyT
  • 1,671
  • 3
  • 21
  • 49
1 2 3
37
38