Site icon LinuxCommands.site

java tutorial: java 8 lambda expression example

Lambda expression is a new feature introduced in java 8.

Lambda expressions are a simplification of anonymous inner classes, a functional programming idea that makes code look cleaner.

For example, previously we used anonymous inner classes to implement code:

Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println("This is an anonymous class.");
    }
};

Using lambda is more concise:

Runnable runnable = () -> System.out.println("This is a Lambda expression.");

Lambda Syntax

(Parameter List) -> {Lambda Function Body}

Description

Examples

No parameters, no return value.

# interface file
package com.example.java8.lambda;

@FunctionalInterface
public interface MyInterface {
    void oprate();
}


# test class
package com.example.java8.lambda;

import org.junit.Test;

public class LambdaTest {
    @Test
    public void test() {
        MyInterface myInterface = () -> {
            System.out.println("Lambda: No parameters, no return value.");
        };
        myInterface.oprate();
    }
}

One parameter has no return value.

Consumer<String> consumer = (x) -> {System.out.println(x);};
consumer.accept("Lambda: One parameter has no return value.");

// Simplified as:
Consumer<String> consumer1 = x -> System.out.println(x);
consumer1.accept("Lambda simplified syntax: One parameter has no return value");

One parameter has no return value.

Function<Integer, Integer> func = (x) -> {return x * x;};
Integer i = func.apply(100);

// Simplified as:
Function<Integer, Integer> func1 = x ->  x * x;
Integer j = func1.apply(100);

Multiple parameters have return values.

BiFunction<Integer, Integer, Integer> biFunction2 = (Integer x, Integer y) -> {return x + y;};
Integer apply2 = biFunction2.apply(100, 200);

//
BiFunction<Integer, Integer, Integer> biFunction = (x, y) -> {return x + y;};
Integer apply = biFunction.apply(100, 200);

// Simplified as:
BiFunction<Integer, Integer, Integer> biFunction1 = (x, y) -> x + y;
Integer apply1 = biFunction1.apply(100, 200);

Exit mobile version