Reputation: 5700
What is the difference of using function method (closure) and normal java method when not using this functional method within a method itself. Any other benefits (e.g. faster access speed)?
version 1:
public class Test{
// does not need to be consumer, can also be
// own function (see version 3)
public static final Consumer<User> addUser = s -> {
// the same logic as in version 2
};
}
version 2:
public class Test{
public static final void addUser(User u) {
// the same logic as in version 1
}
}
version 3:
public class Test{
Function<User, String> addUser= (User e)-> {/* the same logic as in version 2 */;return "saved";};
}
Upvotes: 2
Views: 153
Reputation: 120938
The first time you invoke your Consumer
it will be slower, because your lambda expression will spin a class underneath that will implement Consumer::accept
with the logic that you provided, but that happens only once on the first call.
You can pass around a Consumer
for example, but you can't a method. Well, there are MethodHandles that allow to pass a pointer/reference to a method.
Upvotes: 4