Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Java Lambda Expressions

  • Lambda expressions are introduced in java8, It offer a way to create anonymous functions. Essentially, they allow functions to be treated as if they were regular variables in Java. This implies that it can be used as variables, returned as values from other functions, and passed as arguments to other functions.

  • A function that doesn't need to be part of any specific class; without belonging to any class

  • With Lambda Expressions, you can pass around these functions as if they were regular objects, and they can be executed whenever needed.

Table Of Content

  • Java Lambda Expressions
  • Types of Lambda expressions
  • Problem Without Lambda Expression
  • Java Lambda expressions without parameter
  • Java Lambda expressions of Foreach Loop


Lambda expressions


(parameters) -> expression

or,

(parameters) -> { statements }

The first form is called the "expression lambda," and the second form is called the "block lambda." In both cases, the "parameters" represent the arguments to the lambda expression, and the "- >" this operator separates the body of the lambda expression from parameters.






Example of an expression lambda

 
// Create a lambda expression that returns the square of a number
Function<Integer, Integer> square = (x) -> Y * Y;

In this example, the "Function" interface is used to represent a function that takes an integer as input and returns an integer as output. The lambda expression "(x) -> x * x" is assigned to the "square" variable, which can then be used like any other function.


Example of an block lambda

 
// Create a lambda expression that prints the elements of an array
Consumer<String[]> printArray = (arr) -> {
    for (String element : arr) {
        System.out.println(element);
    }
};




In this example, the "Consumer" interface is used to represent a function that takes an array of strings as input and returns no output. The lambda expression "(arr) -> { for (String element : arr) { System.out.println(element); } }" is assigned to the "printArray" variable.


Example : Without Lambda Expression

import java.util.Scanner;

public class AverageCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("How many numbers do you want to enter? ");
        int count = scanner.nextInt();

        int sum = 0;
        for (int i = 0; i < count; i++) {
            System.out.print("Enter number #" + (i + 1) + ": ");
            int number = scanner.nextInt();
            sum += number;
        }

        double average = (double) sum / count;
        System.out.println("The average of the numbers is: " + average);
    }
}



Output:

How many numbers do you want to enter? 5
Enter number #1: 10
Enter number #2: 20
Enter number #3: 30
Enter number #4: 40
Enter number #5: 50
The average of the numbers is: 30.0 

Lambda expressions


A concise way of expressing a single method interface using an expression. This is helpful in writing functional programming style code.


Java example of Lambda expressions
 // Java example of Lambda expressions 
import java.util.Scanner;
import java.util.stream.IntStream;

public class AverageCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("How many numbers do you want to enter? ");
        int count = scanner.nextInt();

        System.out.print("Enter the numbers separated by spaces: ");
        int[] numbers = IntStream.range(0, count)
                                 .map(i -> scanner.nextInt())
                                 .toArray();

        double average = IntStream.of(numbers)
                                  .average()
                                  .orElse(Double.NaN);

        System.out.println("The average of the numbers is: " + average);
    }
}



Output:

How many numbers do you want to enter? 5
Enter the numbers separated by spaces: 10 20 30 40 50
The average of the numbers is: 30.0 

Java Lambda expressions without parameter

 // Java example of Lambda expressions 
public class NoParameterLambdaExample {
    public static void main(String[] args) {
        Runnable runnable = () -> System.out.println("Hello, world!");
        runnable.run();
    }
}

Output:

Hello, world! 

Java Lambda expressions with Single Parameter

 // Java example of Lambda expressions 
public class SingleParameterLambdaExample {
    public static void main(String[] args) {
        // Using a lambda expression to double a number
        IntUnaryOperator doubleOp = x -> x * 2;
        System.out.println(doubleOp.applyAsInt(5)); // prints "10"
    }
}



Output:

10 

Java Lambda expressions with Multiple Parameters

 // Java example of Lambda expressions 
public class MultipleParametersLambdaExample {
    public static void main(String[] args) {
        // Using a lambda expression to add two numbers
        IntBinaryOperator addOp = (x, y) -> x + y;
        System.out.println(addOp.applyAsInt(3, 5)); // prints "8"
    }
}

Output:

8 

Java Lambda expressions with or without return keyword

 // Java example of Lambda expressions 
public class WithOrWithoutReturnLambdaExample {
    public static void main(String[] args) {
        // Using a lambda expression to add two numbers and return the result
        IntBinaryOperator addOp = (x, y) -> {
            int result = x + y;
            return result;
        };
        System.out.println(addOp.applyAsInt(3, 5)); // prints "8"

        // Using a lambda expression to subtract two numbers without a return statement
        IntBinaryOperator subtractOp = (x, y) -> x - y;
        System.out.println(subtractOp.applyAsInt(5, 3)); // prints "2"
    }
}



Output:

8
2

Java Lambda expressions of Foreach Loop

 // Java example of Lambda expressions 
import java.util.ArrayList;
import java.util.List;

public class ForEachLoopLambdaExample {
    public static void main(String[] args) {
        // Using a lambda expression to print the elements of a list
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        names.forEach(name -> System.out.println(name));
    }
}

Output:

Alice
Bob
Charlie 

Java Lambda expressions with Multiple Statements

 // Java example of Lambda expressions 
public class MultipleStatementsLambdaExample {
    public static void main(String[] args) {
        // Using a lambda expression to print a message with the current date and time
        Runnable runnable = () -> {
            System.out.println("Current date and time:");
            System.out.println(new java.util.Date());
        };
        runnable.run();
    }
}



Output:

Current date and time:
Fri Feb 19 08:50:02 UTC 2021 

Java Lambda expressions to create thread

 // Java example of Lambda expressions 
public class CreatingThreadLambdaExample {
    public static void main(String[] args) {
        // Using a lambda expression to create a new thread
        Thread thread = new Thread(() -> {
            System.out.println("New thread running");
        });
        thread.start();
    }
}

Output:

New thread running 

Java Lambda expressions : Comparator

 // Java example of Lambda expressions 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorLambdaExample {
    public static void main(String[] args) {
        // Using a lambda expression to sort a list of strings in descending order
        List<String> names = new ArrayList<>();
        names.add("Charlie");
        names.add("Bob");
        names.add("Alice");
        Comparator<String> descendingOrder = (s1, s2) -> s2.compareTo(s1);
        Collections.sort(names, descendingOrder);
        System.out.println(names); // prints "[Charlie, Bob, Alice]"
    }
}



Output:

[Charlie, Bob, Alice] 

Java Lambda expressions to Filter Collection Data

 // Java example of Lambda expressions 
import java.util.ArrayList;
import java.util.List;

public class FilterCollectionLambdaExample {
    public static void main(String[] args) {
        // Using a lambda expression to filter a list of integers to only include even numbers
        List<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);
        List<Integer> evenNumbers = new ArrayList<>();
        numbers.forEach((n) -> {
            if (n % 2 == 0) {
                evenNumbers.add(n);
            }
        });
        System.out.println(evenNumbers); // prints "[2, 4]"
    }
}



Output:

[2, 4] 
Method References in Java Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements
Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.