Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

java - 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 + "?";
    }
}
question from:https://stackoverflow.com/questions/65901155/difference-between-two-implementation-with-lambda-expression-and-simple-method-f

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 + "?";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...