Lambda Notes
Lambda Notes
@FunctionalInterface
interface Sayable{
void say(String msg); // abstract method
}
@FunctionalInterface
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
import java.util.function.Function;
// String to an integer
Function < String, Integer > stringToInt = x -> Integer.valueOf(x);
System.out.println(" String to Int: " + stringToInt.apply("4"));
class PersonEntity {
private String name;
private int age;
class PersonDTO {
private String name;
private int age;
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
import java.util.function.Supplier;
Person p = supplier.get();
System.out.println("Person Detail:\n" + p.getName() + ", " +
p.getAge());
}
}
@FunctionalInterface
public interface Consumer<T> {
void accept(T arg0);
listOfPerson.forEach((person) -> {
System.out.println(" Person name : " + person.getName());
System.out.println(" Person age : " + person.getAge());
});
// Second example
Consumer<Person> consumer = (person) -> {
System.out.println(person.getName());
System.out.println(person.getAge());
};
consumer.accept(new Person("Ramesh", 30));
}
}
@FunctionalInterface
public interface BiFunction<T, U, R> {
R apply(T arg0, U arg1);
}
}
@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T arg0, U arg1);
package com.javaguides.java.functionalinterfaces;
import java.util.function.BiPredicate;
@Override
public boolean test(String s1, String s2) {
return s1.equals(s2);
}
};
System.out.println(predicateObject.test("Ramesh", "Ramesh"));
Output:
true
true
false
Summary
A functional interface is an interface that has exactly one abstract
method.
Since default methods have an implementation, they are not abstract so a
functional interface can have any number of them.
If an interface declares an abstract method with the signature of one of
the methods of java.lang.Object, it doesn't count toward the functional
interface method count.
A functional interface is valid when it inherits a method that is equivalent
but not identical to another.
An empty interface is not considered a functional interface.
A functional interface is valid even if
the @FunctionalInterface annotation would be omitted.
Functional interfaces are the basis of lambda expressions.
Arrow Token: The arrow token -> separates the parameters from the
lambda body.
3. Use Cases
Lambda expressions are often used with functional interfaces in
the java.util.function package, such as Predicate, Function, Consumer,
and Supplier. They're also commonly used with the Streams API for
operations like filtering, mapping, and reducing.
interface Drawable{
public void draw();
}
public class LambdaExpressionExample {
public static void main(String[] args) {
int width=10;
//with lambda
Drawable withLambda=()->{
System.out.println("Drawing "+width);
};
withLambda.draw();
}
}
Output :
Drawing 10
If the abstract method takes a single parameter, you can omit the
parentheses around the parameter:
interface Printable {
void print(String msg);
}
Output :
With Lambda: The second part of the code shows how to achieve
the same functionality using a lambda expression. Instead of using an
anonymous class, a lambda expression is assigned to a Runnable
variable, withLambda. This lambda expression has the same
functionality as the anonymous class but is much more concise. A
new thread is created with this lambda expression and started, printing
"Runnable example with lambda exp." to the console.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
Collections.sort(listOfPerson, comparator);
package net.javaguides.collections;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
*
* Java program to demonstrate different ways to Iterate over an
ArrayList in Java
*
*
*/
public class DifferentWaysListIterateProgram {
courses.forEach(DifferentWaysListIterateProgram::printCourse);
}
package net.javaguides.collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Java program to demonstrate different ways to iterate over a Set in
Java
*
* @author Ramesh Fadatare
*
*/
public class DifferentWaysSetIterateProgram {
Set < String > courses = new HashSet < String > ();
courses.add("Java");
courses.add("C");
courses.add("C++");
courses.add("Python");
courses.add("Scala");
package net.javaguides.collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* This program demonstrate different ways to iterate over a Map in
Java
*
* @author Ramesh Fadatare
*
*/
public class DifferentWaysMapIterateProgram {
Map < Integer, String > coursesMap = new HashMap < Integer,
String > ();
coursesMap.put(1, "C");
coursesMap.put(2, "C++");
coursesMap.put(3, "Java");
coursesMap.put(4, "J2EE");
coursesMap.put(5, "Python");
coursesMap.put(6, "Scala");
Example:
ContainingClass::staticMethodName
Example:
containingObject::instanceMethodName
Example:
ContainingType::methodName
4. Reference to a constructor
Example:
ClassName::new
ContainingClass::staticMethodName
Example 1: This example shows, how the lambda expression replaced with
method refers to the static method.
package com.java.lambda;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
class Arithmetic {
public static int add(int a, int b) {
return a + b;
}
containingObject::instanceMethodName
interface Sayable {
void say();
}
Example 2:
package com.java.lambda;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
@FunctionalInterface
interface Printable{
void print(String msg);
}
}
}
import java.util.function.BiFunction;
class Arithmetic {
public int add(int a, int b) {
return a + b;
}
}
Syntax :
ContainingType::methodName
ClassName::new
interface Messageable{
Message getMessage(String msg);
}
class Message{
Message(String msg){
System.out.print(msg);
}
}
Example 2: Write the Lambda to convert List into Set and convert Lambda into
method reference:
// 4. reference to a constructor
List<String> fruits = new ArrayList<>();
// Adding new elements to the ArrayList
fruits.add("Banana");
fruits.add("Apple");
fruits.add("mango");
fruits.add("orange");