How to Use Lambdas in Java

In Java, lambdas are a feature introduced in Java 8 that allow you to treat functionality as a method argument or to create anonymous functions. Lambdas provide a concise way to express instances of single-method interfaces (also known as functional interfaces). Here's how you can use lambdas in Java:

Syntax:

The basic syntax of a lambda expression in Java is as follows:

        
            (parameters) -> expression
        
    

or

        
            (parameters) -> { statements; }
        
    

Where:

  • parameters: The input parameters for the lambda expression.
  • ->: The lambda operator, separates the parameter list from the body of the lambda expression.
  • expression or { statements; }: The body of the lambda expression, which can be an expression or a block of statements.
Examples:
  1. Using Lambda with Functional Interface:

    Suppose you have a functional interface MyInterface with a single abstract method myMethod():

                    
                        interface MyInterface {
                            void myMethod();
                        }                    
                    
                

    You can use a lambda expression to implement this interface:

                    
                        MyInterface obj = () -> System.out.println("Lambda expression implementation");
                        obj.myMethod(); // Output: Lambda expression implementation                    
                    
                

  2. Using Lambda with Parameters:

    You can also use lambdas with parameters:

                    
                        interface AddInterface {
                            int add(int a, int b);
                        }                    
                    
                

                    
                        AddInterface addObj = (int a, int b) -> a + b;
                        System.out.println(addObj.add(3, 5)); // Output: 8                    
                    
                

  3. Using Lambda with Collections:

    Lambdas are often used with collections to perform operations like filtering, mapping, or iterating:

                    
                        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    
                        // Using forEach to iterate through elements
                        numbers.forEach(num -> System.out.println(num));
                        
                        // Using filter to filter even numbers
                        List<Integer> evenNumbers = numbers.stream()
                                                          .filter(num -> num % 2 == 0)
                                                          .collect(Collectors.toList());                    
                    
                

  4. Using Lambda with Comparator:

    You can use lambdas with Comparator for sorting:

                    
                        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
    
                            // Sorting names in ascending order
                            Collections.sort(names, (name1, name2) -> name1.compareTo(name2));                        
                    
                

Note:
  • Lambdas can only be used with functional interfaces, i.e., interfaces with only one abstract method.
  • Lambdas can capture variables from their enclosing scope, but these variables must be effectively final or explicitly marked as final.

These examples demonstrate the basic usage of lambdas in Java. They provide a concise and expressive way to represent functionality as objects.

What are static default methods

In Java, starting from Java 8, interfaces gained the ability to have static and default methods. These additions were introduced to enhance the functionality of interfaces without breaking backward compatibility. Static and default methods in interf …

read more

What is the purpose of LongBinaryOperator functional interface

The LongBinaryOperator functional interface in Java is part of the java.util.function package and is designed to represent an operation that takes two long parameters and produces a result of type long. It is often used in scenarios where you need to …

read more