Call System.out.println () via lambda expression

In C #, I can write the following code:

public static Action<object> WL = x => Console.WriteLine(x); 

... and then every time I want to write something to the console, I just call:

 WL("Some output"); 

What would be the equivalent code using Java 8 lambda expressions? I tried the following and it does not work:

 static void WL = (String s) -> { System.out.println(s); } 
+7
java lambda java-8
source share
2 answers

Your current attempt does not work, because you are trying to declare a variable of type void - the equivalent will not work in C # either. You need to declare a variable of the appropriate functional interface, just like you use the delegate type in C #.

You can do this with a lambda expression, but it would be better (IMO) to use a method reference:

 import java.util.function.Consumer; public class Test { public static void main(String[] args) { Consumer<Object> c1 = x -> System.out.println(x); Consumer<Object> c2 = System.out::println; c1.accept("Print via lambda"); c2.accept("Print via method reference"); } } 

Here, the Consumer<T> interface is generally equivalent to the Action<T> delegate in .NET.

Similarly, you can use method group conversion in C # rather than a lambda expression:

 public static Action<object> WL = Console.WriteLine; 
+15
source share
 interface MyMethod { public void print(String s); } class Main { public static void main(String[] args) { MyMethod method = (String s) -> { }; } } 

In java, lambda expressions revolve around functional interfaces; Interfaces containing only one method.

+1
source share

All Articles