Java 8 pass method as parameter

Currently, you get into Java lambda expressions and method references.

I want to pass a method with no arguments and no return value as an argument to another method. Here is how I do it:

public void one() { System.out.println("one()"); } public void pass() { run(this::one); } public void run(final Function function) { function.call(); } @FunctionalInterface interface Function { void call(); } 

I know that there is a set of predefined functional interfaces in java.util.function , for example, Function<T,R> , but I did not find a single argument without arguments and did not create the result.

+48
java lambda java-8 method-reference
Aug 07 '14 at 15:18
source share
2 answers

It really doesn't matter; Runnable will do too.

 Consumer<Void>, Supplier<Void>, Function<Void, Void> 
+43
Aug 08 '14 at 8:39 on
source share

You can also pass lambda as follows:

 public void pass() { run(()-> System.out.println("Hello world")); } public void run(Runnable function) { function.run(); } 

This way you pass lambda directly as a method.

+28
Sep 07 '15 at 20:53
source share



All Articles