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.
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.
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.
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.
I think InteliJ means replacing
.map(str -> new Gizmo(str))
with
.map(Gizmo::new)
which is a constructor reference. See detailed explanation here.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With