Skip to content
Advertisement

Difference between two implementation with lambda expression and simple method form?

Two bellow snippets with the same output, one with using Functional interface and lambda expression, while the other snippet uses two simple method and easy to understand. What are the benefits first snippet code while it increases complexity.

First:

interface StringFunction {
    String run(String str);
}

public class Main {
    public static void main(String[] args) {
        StringFunction exclaim = (s) -> s + "!";
        StringFunction ask = (s) -> s + "?";
        printFormatted("Hello", exclaim);
        printFormatted("Hello", ask);
    }
    public static void printFormatted(String str, StringFunction format) {
        String result = format.run(str);
        System.out.println(result);
    }
}

Second:

public class Main {
    public static void main(String[] args) {
        System.out.println(exclaim("Hello"));
        System.out.println(ask("Hello"));
    }

    static String exclaim(String s) {
        return s + "!";
    }

    static String ask(String s) {
        return s + "?";
    }
}

Advertisement

Answer

In the first example, you are passing a behaviour which you can change for every call in a much cleaner and succinct way than your second way e.g.

StringFunction exclaim = s -> s + "!";
printFormatted("Hello", exclaim);

exclaim = s -> s + "!!!";
printFormatted("Hello", exclaim);

If you have to do it in your second way, you will have to write another method for it.

On a side note, in your lambda expression, you do not need the parenthesis in case of a single parameter i.e. you can write it simply as (I’ve already done this way in the code above):

StringFunction exclaim = s -> s + "!";
StringFunction ask = s -> s + "?";
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement