@Entity
@Author
@Override - annotation informs the compiler that the element is meant to override an element declared in a superclass.
@SuppressWarnings - annotation tells the compiler to suppress specific warnings that it would otherwise generate.
@Deprecated - annotation indicates that the marked element is deprecated and should no longer be used.
Lambda Expressions: Lambda can be used with certain type of interfaces.
parameter -> expression
(parameter1, parameter2) -> expression
(parameter1, parameter2) -> {expression}
Any interface with a SAM(Single Abstract Method) is a functional interface, and its implementation may be treated as lambda expressions. When a method inside an interface does not have implementation, it is called abstract method. When an interface has one abstract method, the interface is called Functional Interface. Abstract method in the interface uses the lambda expressions. Interface is preceded with Functional Interface Tag
Example Interface:
@Functional Interface
public Interface printable {
void print();
}
For Loop using Lambda Expressions on Array List:
List
names.forEach(name -> System.out.println("Hello, " + name));
For Loop using Lambda Expressions on Hash Map:
Map
ages.put("John", 25);
ages.put("Freddy", 24);
ages.put("Samuel", 30);
ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old"));
Filter list using the Stream API and keep only the names that start with the letter “A”.
List
List
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
System.out.println(namesWithA.get(0).toLowerCase());
System.out.println(namesWithA.get(1).toLowerCase());
Replace All in List: List
names.replaceAll(name -> name.toUpperCase());
names.forEach(name -> System.out.println("Hello, " + name));
Replace All in HashMap: Map
salaries.put("John", 40000);
salaries.put("Freddy", 30000);
salaries.put("Samuel", 50000);
salaries.replaceAll((name, oldValue) ->
name.equals("Freddy") ? oldValue : oldValue + 10000);
salaries.forEach((name, value) -> System.out.println(name + " is " + value + " years old"));
Calculator Operations using Lambda Expressions:
package org.example;
public class Main {
@FunctionalInterface
interface Operation {
int calculate(int x);
}
public static void main(String[] args) {
int a = 5;
Operation square = (int x) -> x * x;
Operation add = (int x) -> x + x;
Operation subtract = (int x) -> x - x;
int ans = square.calculate(a);
int addedvalue = add.calculate(a);
System.out.println(ans);
System.out.println(addedvalue);
System.out.println(subtract.calculate(6));
}
}
No comments:
Post a Comment