Skip to content

Instantly share code, notes, and snippets.

@ucguy4u
Last active September 18, 2020 17:56
Show Gist options
  • Save ucguy4u/48289ec65acc143292d0d212f7973e4e to your computer and use it in GitHub Desktop.
Save ucguy4u/48289ec65acc143292d0d212f7973e4e to your computer and use it in GitHub Desktop.
This program explains the syntax of using lambda expressions in Java
package com.ucguy4u.functional.java;
import java.util.Arrays;
import java.util.function.BiFunction;
import java.util.function.Consumer;
/**
*
* @author chauhanuday
*/
public class Lambdas_01 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// Anonymous Inner Class: Runnable
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("Thread 1 is running");
}
};
// Lambda version of Runnable (no arguments)
Runnable r2 = () -> System.out.println("\nThread 2 is running");
// Start both threads
r1.run();
r2.run();
// using an existing functional interface BiFunction
BiFunction<String, String, String> concat = (a, b) -> a + b;
String sentence = concat.apply("Today is ", "a great day");
System.out.println("\n" + sentence + "\n");
// example of the Consumer functional interface
Consumer<String> hello = name -> System.out.println("Hello, " + name);
for (String name : Arrays.asList("Duke", "Mickey", "Minnie")) {
hello.accept(name);
}
// example of passing one value
GreetingFunction greeting = message -> System.out.println("\nJava Programming " + message);
greeting.sayMessage("Rocks with lambda expressions");
}
// custom functional interface
@FunctionalInterface
interface GreetingFunction {
void sayMessage(String message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment