Java 8 Lambda Expressions | Code Factory

Syntax

Java Example without Lambda Expression

interface Drawable {
public void draw();
}
public class Main {
public static void main(String[] args) {
int width = 10;
// without lambda, Drawable implementation using anonymous class
Drawable d = new Drawable() {
public void draw() {
System.out.println("Drawing " + width);
}
};
d.draw();
}
}

Java Example with Lambda Expression

@FunctionalInterface
// It is optional
interface Drawable {
public void draw();
}
public class Main {
public static void main(String[] args) {
int width = 10;
// with lambda
Drawable d2 = () -> {
System.out.println("Drawing " + width);
};
d2.draw();
}
}

Java Lambda Expression Example: No Parameter

interface Sayable {
public String say();
}
public class Main {
public static void main(String[] args) {
Sayable s = () -> {
return "I have nothing to say.";
};
System.out.println(s.say());
}
}

Java Lambda Expression Example: Single Parameter

interface Sayable {
public String say(String name);
}
public class Main {
public static void main(String[] args) {
// Lambda expression with single parameter.
Sayable s1 = (name) -> {
return "Hello, " + name;
};
System.out.println(s1.say("Code"));
// You can omit function parentheses
Sayable s2 = name -> {
return "Hello, " + name;
};
System.out.println(s2.say("Factory"));
}
}

Java Lambda Expression Example: Multiple Parameters

interface Addable {
int add(int a, int b);
}
public class Main {
public static void main(String[] args) {
// Multiple parameters in lambda expression
Addable ad1 = (a, b) -> (a + b);
System.out.println(ad1.add(10, 20));
// Multiple parameters with data type in lambda expression
Addable ad2 = (int a, int b) -> (a + b);
System.out.println(ad2.add(100, 200));
}
}

Java Lambda Expression Example: Foreach Loop

public class Main {
public static void main(String[] args) {
List<string> list = new ArrayList<string>();
list.add("Code");
list.add("Factory");
list.forEach((n) -> System.out.println(n));
}
}

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Why Spring Boot is called opinionated?

Unit Testing Apache Camel

Adapter Design Pattern in Java

How to Initialize Cache Data from Databases in Spring Boot