Lambda Expressions: Reducing Java Lambda Expressions

What we’ll cover:

Functional Interfaces

| Name | Has Return-Value | Takes Argument 1 | Takes Argument 2 | |————|———|——————|——————| | Runnable | No | No | No | | Supplier | Yes | No | No | | Consumer | No | Yes | No | | BiConsumer | No | Yes | Yes | | Function | Yes | Yes | No | | BiFunction | Yes | Yes | Yes |

Functional Interfaces

Function as BiFunction

public void demo() {
  Function<Integer, String> function
    = (intVal) -> intVal.toString();

  BiFunction<Integer, Object, String> biFunction
    = (intVal, obj) -> intVal.toString();
}

Function as BiFunction

public void demo() {
  Function<Integer, String> function
    = (intVal) -> intVal.toString();

  BiFunction<Integer, Object, String> biFunction
    = (intVal, obj) -> function.apply(intVal);
}

BiConsumer as BiFunction

public void demo() {
    BiConsumer<Integer, String> consumer = (intVal, stringVal) ->
            System.out.println(intVal + stringVal);

    BiFunction<Integer, String, Object> biFunction = (intVal, stringVal) -> {
        System.out.println(intVal + stringVal);
        return null;
    };
}

BiConsumer as BiFunction

public void demo() {
    BiConsumer<Integer, String> consumer = (intVal, stringVal) ->
            System.out.println(intVal + stringVal);

    BiFunction<Integer, String, Object> biFunction = (intVal, stringVal) -> {
        consumer.accept(intVal, stringVal);
        return null;
    };
}

Consumer as BiConsumer

public void demo() {
  Consumer<String> consumer = (name) -> System.out.println("Hello " + name);
  BiConsumer<String, Object> = (name, obj) -> System.out.println("Hello " + name);
}

Consumer as BiConsumer

public void demo() {
  Consumer<String> consumer = (name) -> System.out.println("Hello " + name);
  BiConsumer<String, Object> = (name, obj) -> consumer.accept(name);
}

Predicate as Function

public void demo() {
    Predicate<String> predicate = (string) ->
        string.startsWith("A");

    Function<String, Boolean> function = (string) ->
        string.startsWith("A");
}

Predicate as Function

public void demo() {
    Predicate<String> predicate = (string) ->
        string.startsWith("A");

    Function<String, Boolean> function = (string) ->
        predicate.test(string);
}

Supplier as Function

public void demo() {
    Supplier<String> supplier = () ->
        String.valueOf(System.currentTimeMillis());

    Function<String, Boolean> function = (obj) ->
        String.valueOf(System.currentTimeMillis());
}

Supplier as Function

public void demo() {
    Supplier<String> supplier = () ->
        String.valueOf(System.currentTimeMillis());

    Function<String, Boolean> function = (obj) ->
        supplier.get();
}

Runnable as Supplier