Introduction to Java Lambda Expressions with Examples

Answered using GPT-4o-mini by Java Q&A Hub

Question:

Introduce Java Lambda Expressions and give examples

Answer:

Java Lambda Expressions, introduced in Java 8, provide a clear and concise way to represent a function interface (an interface with a single abstract method) using an expression. They enable you to treat functionality as a method argument, or to create a concise way to express instances of single-method interfaces (functional interfaces).

Key Features of Lambda Expressions:

  1. Conciseness: They reduce the verbosity of anonymous inner classes.
  2. Readability: They make the code more readable and expressive.
  3. Functional Programming: They enable functional programming features in Java, such as passing behavior as parameters.

Syntax of Lambda Expressions:

The basic syntax of a lambda expression is:

(parameters) -> expression

or

(parameters) -> { statements; }

Components:

  • Parameters: The input parameters for the lambda expression. The type can be inferred, so you can omit it.
  • Arrow Token (->): Separates the parameters from the body.
  • Body: The code that gets executed. It can be a single expression or a block of statements.

Example of Lambda Expressions:

  1. Basic Example: Here’s a simple example of a lambda expression that takes two integers and returns their sum.

    // Functional interface
    interface MathOperation {
        int operation(int a, int b);
    }
    
    public class LambdaExample {
        public static void main(String[] args) {
            // Lambda expression for addition
            MathOperation addition = (a, b) -> a + b;
    
            System.out.println("10 + 5 = " + addition.operation(10, 5));
        }
    }
    
  2. Using Lambda with Collections: You can use lambda expressions with Java's collection framework, such as filtering a list.

    import java.util.Arrays;
    import java.util.List;
    
    public class LambdaWithCollections {
        public static void main(String[] args) {
            List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
    
            // Using lambda expression to filter names starting with 'A'
            names.stream()
                 .filter(name -> name.startsWith("A"))
                 .forEach(name -> System.out.println(name));
        }
    }
    
  3. Using Lambda with Runnable: You can also use lambda expressions to implement functional interfaces like Runnable.

    public class LambdaRunnable {
        public static void main(String[] args) {
            // Lambda expression for Runnable
            Runnable runnable = () -> System.out.println("Running in a thread");
    
            // Starting a new thread
            Thread thread = new Thread(runnable);
            thread.start();
        }
    }
    
  4. Using Lambda with Comparator: Lambda expressions can simplify the implementation of the Comparator interface.

    import java.util.Arrays;
    import java.util.Comparator;
    
    public class LambdaComparator {
        public static void main(String[] args) {
            String[] names = {"John", "Alice", "Bob", "Charlie"};
    
            // Sorting using lambda expression
            Arrays.sort(names, (a, b) -> a.compareTo(b));
    
            // Printing sorted names
            for (String name : names) {
                System.out.println(name);
            }
        }
    }
    

Conclusion:

Java Lambda Expressions provide a powerful way to write more concise and readable code, especially when working with functional interfaces and collections. They are a key feature of Java 8 and beyond, enabling developers to adopt a more functional programming style.