Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm told to convert a lambda with a parameterized constructor to a method reference

Lets say I have a class Gizmo with a constructor that takes a String. Lets say I want to convert a List<String> to a List<Gizmo>.

I might write:

List<String> strings = new ArrayList<>();
List<Gizmo> gizmos = strings
        .stream()
        .map(str -> new Gizmo(str))
        .collect(Collectors.toList());

Now, the problem is that I'm told by IntelliJ that I can replace the lambda with a method reference. Thing is, I'm pretty sure method references can't take parameters.

like image 522
AaronF Avatar asked May 18 '17 00:05

AaronF


People also ask

How do I change lambda with method reference?

If you are using a lambda expression as an anonymous function but not doing anything with the argument passed, you can replace lambda expression with method reference. In the first two cases, the method reference is equivalent to lambda expression that supplies the parameters of the method e.g. System.

Does it make sense to replace lambda expression with method references?

To summarize: If the purpose of the lambda expression is solely to pass a parameter to an instance method, then you may replace it with a method reference on the instance. If the pass-through is to a static method, then you may replace it with a method reference on the class.

How do you pass a lambda expression as a parameter?

Passing Lambda Expressions as Arguments If you pass an integer as an argument to a function, you must have an int or Integer parameter. If you are passing an instance of a class as a parameter, you must specify the class name or the object class as a parameter to hold the object.


2 Answers

I think InteliJ means replacing

.map(str -> new Gizmo(str))

with

.map(Gizmo::new)

which is a constructor reference. See detailed explanation here.

like image 54
Sergey Kalinichenko Avatar answered Jan 04 '23 05:01

Sergey Kalinichenko


Now, the problem is that I'm told by IntelliJ that I can replace the lambda with a method reference.

it simply means you can change this:

.map(str -> new Gizmo(str))

to this:

.map(Gizmo::new)

you can read more about Constructor method reference.

like image 33
Ousmane D. Avatar answered Jan 04 '23 06:01

Ousmane D.