[go: up one dir, main page]

0% found this document useful (0 votes)
23 views13 pages

Java U-3 Lec-4 Notes (Th+P+Ex)

Uploaded by

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

Java U-3 Lec-4 Notes (Th+P+Ex)

Uploaded by

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

What We will Discuss Today?

• What is Lambda Expressions in Java?


• Why we use Lambda Expressions?
• Benefits of Lambda Expressions.
• Examples
• Exercise
What is Lambda Expressions and why we use them including benefits?
Lambda expressions are a powerful feature introduced in Java 8, primarily aimed at simplifying the syntax required for using
interfaces with a single abstract method, known as functional interfaces.

They allow you to treat functionality as a method argument, or to create anonymous functions.

Here are some key points about lambda expressions in Java:

1. Concise Syntax: Lambda expressions provide a concise way to represent anonymous functions. They remove the need for
verbose anonymous inner classes when implementing single-method interfaces.

2. Functional Interfaces: Lambda expressions are commonly used with functional interfaces, which are interfaces with only one
abstract method. Examples of functional interfaces in Java include Runnable, Comparator, and Callable.

3. Type Inference: Java can often infer the types of parameters in lambda expressions. If the type can be inferred from the
context, you can omit the type declarations.

4. Target Typing: The type of the lambda expression is inferred by the target type, which is usually a functional interface.

5. Capturing Variables: Lambda expressions can capture variables from their enclosing scope. These variables must be
effectively final, meaning they are not reassigned after initialization.
What is Lambda Expressions and why we use them including benefits?
6. Improved Readability: By eliminating the need for verbose anonymous inner classes, lambda expressions
make code more readable and maintainable, especially for small, single-purpose methods.

7. Flexibility: Lambda expressions allow for the representation of behavior as data, enabling more flexible
and expressive programming constructs. They can be passed as arguments to methods, stored in data
structures, and returned from methods, allowing for functional programming paradigms.

8. Performance Optimization: Lambda expressions can enable performance optimizations in certain cases,
such as avoiding the overhead of creating new classes for anonymous inner classes. They can also
facilitate parallel execution and lazy evaluation in functional programming constructs like streams.

Overall, lambda expressions enhance Java's expressive power, promote functional programming practices, and
lead to more concise and readable code, ultimately improving developer productivity and code
maintainability.
Syntax of Lambda Expressions
Syntax: Lambda expressions have a simple syntax:

(parameters) -> expression


Or
(parameters) -> { statements; }
Examples
List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); Collections.sort(names, (a, b) ->
a.compareTo(b));

Runnable r = () -> { System.out.println("This is a lambda expression."); };

Thread t = new Thread(() -> {


System.out.println("This is a lambda running in a thread."); });
t.start();
Examples

interface MathOperation
{
int operate(int a, int b);
}
MathOperation addition = (int a, int b) -> a + b; System.out.println(addition.operate(5, 3)); // Output: 8

Map<String, Integer> ages = new HashMap<>();


ages.put("Alice", 30);
ages.put("Bob", 25);
ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old"));

List<Person> people = Arrays.asList( new Person("Alice", 30), new Person("Bob", 25), new
Person("Charlie", 35) ); people.sort(Comparator.comparing(Person::getName));
Consumer Interface
The Consumer interface is a part of the java.util.function package introduced in Java 8 as a part of the functional
programming enhancements. It represents an operation that accepts a single input argument and returns no result.
It's a functional interface because it specifies a single abstract method called

accept(T t),

where T is the type of the input argument.

Here's the declaration of the Consumer interface:

@FunctionalInterface

public interface Consumer<T>

void accept(T t);

}
Example
import java.util.Arrays;

import java.util.List;

import java.util.function.Consumer;

public class Main {

public static void main(String[] args) {

List<String> names = Arrays.asList(“UP", “Delhi", “MP");

// Using a Consumer to print each element

Consumer<String> ff = name -> System.out.println(name);

names.forEach(ff);

}
Example
interface FuncInterface
{
// An abstract function void abstractFun(int x);
}

Class A
{
public static void main(String args[])
{
FuncInterface fobj = (int x)->System.out.println(2*x);
fobj.abstractFun(5);
}
}
Lambda Expression Parameters
• Zero Parameter
• () -> System.out.println("Zero parameter lambda");

• Single Parameter
• (a) -> System.out.println(“Single parameter: " + a);

• Multiple Parameters
• (p1, p2) -> System.out.println("Multiple parameters: " +(p1+p2));
Think Reverse
() -> System.out.println("Hello");
It takes interface of the following form:
interface A
{
public void print()
}
(a) -> System.out.println(“A=“+a);
It takes interface of the following form:
interface A
{
public void print(T t)
}
Exercise
1. WAP using lambda expression to find the sum of two integers.

2. WAP using lambda expression to check if a given string is empty.

3. WAP using lambda expression to convert a list of strings to uppercase and lowercase.

4. WAP using lambda expression to filter out even and odd numbers from a list of integers.

5. WAP using lambda expression to sort a list of strings in alphabetical order.

6. WAP using lambda expression to find the average of a list of doubles.

7. WAP using lambda expression to remove duplicates from a list of integers.

8. Write a lambda expression to implement a lambda expression to calculate the factorial of a given number.

9. WAP using lambda expression to create a lambda expression to check if a number is prime.

10. WAP using lambda expression to concatenate two strings.

11. WAP using lambda expression to find the maximum and minimum values in a list of integers.

12. Write a Java program to create a lambda expression to multiply and sum all elements in a list of integers.
Exercise
13. WAP using lambda expression to count words in a sentence.

14. WAP using lambda expression to check if a given string is a palindrome.

15. WAP using lambda expression to calculate the sum of squares of all odd and even numbers in a list.

16. WAP using lambda expression to check if a list of strings contains a specific word.

17. WAP using lambda expression to find the length of the longest and smallest string in a list.

18. WAP using lambda expression to check if a given number is a perfect square.

19. WAP using lambda expression to find the second largest and smallest element in an array.

20. WAP using lambda expression to sort a list of objects based on a specific attribute.

21. WAP using lambda expression to calculate the sum of all prime numbers in a given range.

22. WAP using lambda expression to check if a list of strings are all uppercase or all lowercase or mixed case.

23. WAP using lambda expression to find the average length of strings in a list.

24. WAP using lambda expression to find the largest prime factor of a given number.

25. WAP using lambda expression to convert an integer to their corresponding binary representation.

You might also like