My quest is how can I have an lambda expression as a parameter in a function?? My intention is, when I execute the sum method the parameter in method accept is taken and used by the object continuation (am I right??), well my doubt is how can I do to make this object continuation a lambda expression which uses the result of value1 + value2, and do something else after that??
Like X.sum(1,2,resultOfSum->{system.out.println(resultOfSum);});
(I've tried this and eclipse make it like an error)
Sorry my english is not so good.
This is my Code.
public class ExampleClass {
public static void main(String[] args) {
X x = new X();
int nro ;
x.sum(1,2,"AN EXAMPLE OF LAMBDA"));
}
}
public class X{
public void sum(int value1,int value2,Consumer<Integer> continuation)
{
continuation.accept(value2+value1);
}}
Interestingly enough, your current lambda expression will work for this (barring the fix to the typo of system.out.println). The below is merely a more concise way to express it.
Effectively, you're writing out a method that takes in two values, produces one, and places it in some sort of consumer. That consumer could be a collection, some function that can handle the result, or another object.
Let's take lambdas out of the equation for a moment and write this out with an anonymous class.
x.sum(1, 2, new Consumer<Integer>() {
@Override
public void accept(final Integer value) {
// what should go here?
}
});
We need to tell this result where to go. We've got a few options:
Collection (List, Set, etc)Let's take the simplest approach and simply print it out.
x.sum(1, 2, new Consumer<Integer>() {
@Override
public void accept(final Integer value) {
System.out.println(value);
}
});
Now, this makes some sense - we're taking the result of two numbers, adding them together, and then printing the result to the screen.
Let's put lambdas back into the mix. This can be expressed in terms of a lambda in this manner:
x.sum(1, 2, System.out::println);
Effectively, whatever resultant value we get back, we wish to then allow the println method to consume it.
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