0% found this document useful (0 votes)
1 views

Java Lambda Expressions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Java Lambda Expressions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Java Lambda Expressions

• Lambda Expressions were added in Java 8.

A lambda expression is a short block of code which takes in parameters and returns a
value. Lambda expressions are similar to methods, but they do not need a name and they
can be implemented right in the body of a method.
Syntax
• The simplest lambda expression contains a single parameter and an
expression:
parameter -> expression
• To use more than one parameter, wrap them in parentheses:
(parameter1, parameter2) -> expression
• Import java.util.ArrayList;
• public class Main {
• public static void main(String[] args) {
• ArrayList<Integer> numbers = new ArrayList<Integer>();
• numbers.add(5);
• numbers.add(9);
• numbers.add(8);
• numbers.add(1);
• numbers.forEach( (n) -> { System.out.println(n); } );
• }
•}
Method references in Java
• Method references in Java provide a shorthand syntax for calling
methods. They allow you to refer to methods without executing them
and are often used to make your code more readable when dealing
with functional programming and lambda expressions.
• Types of Method References
There are four types of method references in Java:
1.Reference to a static method
2.Reference to an instance method of a particular object
3.Reference to an instance method of an arbitrary object of a particular
type
4.Reference to a constructor
• Syntax
• The syntax for method references uses the :: operator
• ClassName::methodName
• import java.util.function.Consumer;
• public class StaticMethodReferenceExample {
• public static void main(String[] args) {
• Consumer<String> printer = MyUtils::printMessage;
• printer.accept("Hello, static method reference!");
• }
•}

You might also like