This is the 11th day of my participation in Gwen Challenge
Simple Lambda expressions – for JAVA beginners
- Components of a Lambda expression
- Some sample implementation and output
- Lambda expressions in functional interfaces
- Lambda expressions in hash mappings
- Lambda expressions for running threads
- Lambda expressions to compare and filter collection lists
- A few points to note when using Lambda expressions
- Why Lambda expressions
- The related content
A Lambda expression is a small piece of code that takes an argument and returns a value. The following example expression takes one parameter. The expression can also contain two or more arguments.
parameter -> expression
Copy the code
Lambda expressions can also be considered anonymous functions. A function that has no name and does not belong to any class. Lambda expressions are similar to methods, but they do not need names and can be implemented in the method body.
(parameter1, parameter2) -> expression
Copy the code
The concept of Lambda expressions was first introduced in the LISP programming language. Expressions are finite. They must return a value immediately, and cannot contain variables such as if or, assignments, or the statement for. To perform more complex operations, blocks of code can be used with curly braces.
(parameter_list) -> {function_body}
Copy the code
If a lambda expression needs to return a value, the code block should have a return statement.
Components of a Lambda expression
A Lambda expression typically consists of the following three components:
- Argument-list: This Argument is usually a list. It can also be empty or non-empty.
- Arrow mark: Used to link the parameter list to the expression body.
- Body: This contains expressions and statements for lambda expressions. The body can be a simple statement or it can contain blocks of code.
Some sample implementation and output
For the first example, we’ll start with a list of numbers. We’ll do some math on the contents of this list.
// A Java program to demonstrate simple lambda expressions
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Creating an ArrayList with elements
// add elements{7,4,2} to the list
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(7);
numbers.add(4);
numbers.add(2);
//Using Lambda to print out all elements
numbers.forEach( n -> System.out.println(n));
//Using Lambda to print out the double value of each element
numbers.forEach( n -> System.out.println(n+n));
//Using Lambda to print all even elements
numbers.forEach( n -> {if (n%2= =0) System.out.println(n);});
}
}
Copy the code
In the Java class above, we have three different Lambda expressions.
- The first expression iterates through the list and prints out each value on a new line.
- The second prints out each element plus its own value.
- The third prints only even numbers.
Output 1
7
4
2
Copy the code
The output of 2
14
8
4
Copy the code
The output of 3
4
2
Copy the code
Lambda expressions in functional interfaces
For these next examples, we will use functional interfaces. A functional interface in Java is an interface that contains only an abstract (unimplemented) method. Functional interfaces can also contain default and static methods with implementations.
- Function interface with no parameters
interface MyFunctionalInterface {
//A method with no parameter
public String sayHello(a);
}
public class ExampleOne {
public static void main(String args[]) {
// lambda expression
MyFunctionalInterface message = () -> {
return "Hello"; }; System.out.println(message.sayHello()); }}Copy the code
The output
Hello
Copy the code
- A functional interface with one parameter
interface MyFunctionalInterface {
//A method with one parameter
public String sayHelloName(String str);
}
public class ExampleTwo {
public static void main(String args[]) {
// lambda expression
MyFunctionalInterface message = (str) -> {
return "Hello " + str;
};
System.out.println(message.sayHelloName("Joy")); }}Copy the code
The output
Hello Joy
Copy the code
- A functional interface with multiple parameters
interface MyFunctionalInterface {
//A method with one parameter
public String concatStrings(String str1, String str2);
}
public class ExampleThree {
public static void main(String args[]) {
// lambda expression
MyFunctionalInterface message = (str1, str2) -> {
return str1 + str2;
};
System.out.println(message.concatStrings("Good "."Day")); }}Copy the code
The output
Good Day
Copy the code
Lambda expressions in hash mappings
Lambda expressions can also be used in hash maps to iterate over elements of a Map or make computational changes. Let’s look at this example below.
public class HashMapExample{
public static void main(String[] args) {
// Creating a HashMap and putting in elements
Map<String, Integer> prices = new HashMap<>();
prices.put("Apple".50);
prices.put("Orange".20);
prices.put("Banana".10);
prices.put("Grapes".40);
//Using Lambda to print out all elements, k=key,v=value
prices.forEach((k,v)->System.out.println("Fruit: " + k + ", Price: "+ v)); }}Copy the code
The output
Fruit: Apple, Price: 50
Fruit: Orange, Price: 20
Fruit: Banana, Price: 10
Fruit: Grapes, Price: 40
Copy the code
Lambda expressions for running threads
You can use lambda expressions to run threads. In the following example, we implement the run method by using lambda expressions.
public class ThreadExample{
public static void main(String[] args) {
//Thread Example without lambda
Runnable r1=new Runnable(){
public void run(a){
System.out.println("Thread1 is running..."); }}; Thread t1=new Thread(r1);
t1.start();
//Thread Example with lambda
Runnable r2=()->{
System.out.println("Thread2 is running...");
};
Thread t2=newThread(r2); t2.start(); }}Copy the code
The output
Thread1 is running...
Thread2 is running...
Copy the code
Lambda expressions to compare and filter collection lists
Lambda expressions can also be used as comparators and can be used to filter lists.
class Product{
int id;
String name;
float price;
public Product(int id, String name, float price) {
super(a);this.id = id;
this.name = name;
this.price = price; }}public class FilterListExample{
public static void main(String[] args) {
List<Product> list=new ArrayList<Product>();
list.add(new Product(1."Volvo".19000f));
list.add(new Product(3."Tesla".75000f));
list.add(new Product(2."Toyota".38000f));
// using lambda to filter data
Stream<Product> filtered_data = list.stream().filter(p ->
p.price > 3000);
// using lambda to iterate through collection
filtered_data.forEach(
product -> System.out.println(product.name+":"+product.price) ); }}Copy the code
The output
Tesla: 75000.0
Toyota: 38000.0
Copy the code
A few points to note when using Lambda expressions
- The body of a Lambda expression can contain zero, one, or more statements.
- If there is only one statement, curly braces are unnecessary and the return type of the anonymous function is the same as that of the body expression.
- If there are multiple statements, they must be enclosed in braces (a code block) and the return type of the anonymous function is the same type as the value returned within the code block; Void is returned if no value is returned
Why Lambda expressions
These are some of the benefits of using Lambda expressions.
1. Fewer lines of code: One of the benefits of using lambda expressions is the reduced amount of code.
2. Support sequential and parallel execution by passing behavior in methods: With the introduction of the Stream API in Java 8, functions can be passed to collection methods, which are now responsible for processing elements either sequentially or in parallel.
3. Greater efficiency (with multi-core cpus) : If you are working on collections in batches, you can achieve greater efficiency (parallel execution) using the Stream API and lambda expressions. Similarly, lambda expressions can help implement internal iterations of collections, rather than external iterations as shown in the example above. Today, we have cpus with multiple cores, so we can take advantage of them by using lambda parallel processing collections.
Anyway, Lambda expressions are welcome to be added to any code base, and this article aims to show how to use and apply their Pointers.
More relevant articles and my contact information are listed here:
github.com/wanghao221
And finally, don’t forget ❤ or 📑