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
4 answers

Passing a method reference as parameter

In a case like this: public class Order { List prices = List.of(1.00, 10.00, 100.00); List pricesWithTax = List.of(1.22, 12.20, 120.00); Double sumBy(/* method reference */) { Double sum = 0.0; for…
Couper
  • 414
  • 5
  • 13
0
votes
2 answers

Grouping a map by object's property to a new Map

First things first, let me add the actual "example code": Map> allCarsAndBrands = new HashMap(); final String bmwBrandName = "BMW"; final String audiBrandName = "AUDI"; List bmwCars = new ArrayList(); bmwCars.add(new…
dNurb
  • 385
  • 2
  • 16
0
votes
1 answer

Java Consumer MethodReference for nonstatic methods

Code snippet: class Scratch { Map> consumerMapping = Map.of( ActionType.REJECT, DocumentPublisher::rejectDocument, ActionType.ACCEPT, DocumentPublisher::acceptDocument, …
migAlex
  • 273
  • 3
  • 16
0
votes
3 answers

How is this method reference valid?

class Dish { public int getCalories() { return calories; } public static final List menu = Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT), new Dish("beef", false, 700, Dish.Type.MEAT), new…
karan mirani
  • 168
  • 1
  • 3
  • 7
0
votes
2 answers

Failing the mock method return with arguments as Parameter

I am failing to write a Test because the answer of my when().thanReturn() is not returning anything. I am not able to mock the behavior (Setup is Spring Boot, Java 8, Junit 4). The problem is that the Method being called is taking method References…
0
votes
1 answer

Java java.util.function.Consumer when argument needs to be transformed

I would like to create a lambda replacement for this current code: Map executionMap = new HashMap<>(); executionMap.put("operation1", str -> this.getEntity().setBooleanCondition(Boolean.parseBoolean(str)) For cases where I don't…
Pat
  • 5,761
  • 5
  • 34
  • 50
0
votes
1 answer

Get Property that has max Character size from list of objects java

I have an List where i will be getting those values from db. I need to find the max character size of a specific field which will be dynamic. For now im able to get the max size of firstName but its kind of hardcoded as shown below. …
0
votes
1 answer

Groovy v3 method reference and groovyString dynamic variable resolution priority if you explicitly set the MethodClosure delegate

I am using Groovy v3.0.1. I am seeing a response I had not expected from the following code. I build a map of verb, noun and closures. The first time I use the methodReference mybed::trySleep as the closure to be passed, but set the delegate to be…
WILLIAM WOODMAN
  • 1,185
  • 5
  • 19
  • 36
0
votes
3 answers

Supplier interface for constructor reference

the following code Supplier newString = String::new; System.out.println(newString.get()); // prints an empty string (nothing) to the console and then a newline character and for the definition of Supplier get method T get() the get method…
user1169587
  • 1,104
  • 2
  • 17
  • 34
0
votes
0 answers

Which is better way to instantiation a java class considering the performance, reflection or Constructor reference?

I have ended up in a situation, where I can use reflection to get a Constructor object and then using that Constructor to instantiate a class or I can use Constructor reference to instantiate it. I wanted to know which is better in terms of…
0
votes
1 answer

Is it legal and defined to pass a method reference to a non-overriding derived class method to its base class?

Is it legal and defined to pass a method reference to a non-overriding derived class method to its base class? public class Base { private Supplier intSupplier; public Base(Supplier intSupplier) { this.intSupplier =…
tpdi
  • 34,554
  • 11
  • 80
  • 120
0
votes
1 answer

Stream map with Generic type

I want clean Sonar issue after create new code in java 8. public class Argument { ... public T getValue() { return parameterType.transform(group.getValues()); } ... } My code: List> args =…
Stéphane GRILLON
  • 11,140
  • 10
  • 85
  • 154
0
votes
0 answers

Java streams equivalent of C# linq property name?

In C# we can obtain a property, field or method name in runtime, like below: Condition(v => v.Locked); where Locked is one of UserEntity properties and v=>v.Locked will be sent to a method and finally we can get name of property…
Homayoun Behzadian
  • 1,053
  • 9
  • 26
0
votes
1 answer

Why does an action listener gives different result when using method reference?

Today, i came across a strange (for me) behavior and i checked it. I did read a bunch of topics about the difference between a method reference and a lambda, but i cannot connect it with my example. Consider the following class: public class…
George Z.
  • 6,643
  • 4
  • 27
  • 47
0
votes
1 answer

What does it mean to surround a method reference with brackets?

I'm using Java 8. I know it's new features like lambda, method references, etc. But I'm confused about this code: static class SRoad implements Comparable { int id; public SRoad(int id) { this.id = id; } @Override …
Neo
  • 1,031
  • 2
  • 11
  • 27