Java 8 Lambda Void argument

Published by user on

Java 8 Lambda Void argument becomes mandatory even if you don’t want to pass it. In this post, we will look at how to remove it using a helper method in the interface.

interface MyInterface<T, U> {
	U action(T t);

	public static MyInterface<Void, Void> helperMethod(Runnable runnable) {
		runnable.run();
		return null;
	}
}

Let’s see how to call the action method with Void argument v.

public class CallLambda {

	public static void main(String[] args) {
		MyInterface<Void, Void> a = (Void v) -> {
			System.out.println("Call With Void argument!!!");
			return null;
		};
	}

}

How to remove the Void argument while using Lambda?

We can easily do this with the helperMethod(). Let’s see how to use it.

public class CallLambda {
	public static void main(String[] args) {
		MyInterface<Void, Void> action = MyInterface
				.helperMethod(() -> System.out.println("Call without Void Argument"));
	}
}

Output:

Call without Void Argument

In short, we can use the Runnable interface to remove the Void argument.

Categories: Java