Do lambda expressions have any use other than saving lines of code?

后端 未结 9 1483
我寻月下人不归
我寻月下人不归 2020-11-29 18:23

Do lambda expressions have any use other than saving lines of code?

Are there any special features provided by lambdas which solved problems which weren\'t easy to s

相关标签:
9条回答
  • 2020-11-29 18:39

    Yes many advantages are there.

    • No need to define whole class we can pass implementation of function it self as reference.
      • Internally creation of class will create .class file while if you use lambda then class creation is avoided by compiler because in lambda you are passing function implementation instead of class.
    • Code re-usability is higher then before
    • And as you said code is shorter then normal implementation.
    0 讨论(0)
  • 2020-11-29 18:41

    One thing I don't see mentioned yet is that a lambda lets you define functionality where it's used.

    So if you have some simple selection function you don't need to put it in a separate place with a bunch of boilerplate, you just write a lambda that's concise and locally relevant.

    0 讨论(0)
  • 2020-11-29 18:46

    Internal iteration

    When iterating Java Collections, most developers tend to get an element and then process it. This is, take that item out and then use it, or reinsert it, etc. With pre-8 versions of Java, you can implement an inner class and do something like:

    numbers.forEach(new Consumer<Integer>() {
        public void accept(Integer value) {
            System.out.println(value);
        }
    });
    

    Now with Java 8 you can do better and less verbose with:

    numbers.forEach((Integer value) -> System.out.println(value));
    

    or better

    numbers.forEach(System.out::println);
    

    Behaviors as arguments

    Guess the following case:

    public int sumAllEven(List<Integer> numbers) {
        int total = 0;
    
        for (int number : numbers) {
            if (number % 2 == 0) {
                total += number;
            }
        } 
        return total;
    }
    

    With Java 8 Predicate interface you can do better like so:

    public int sumAll(List<Integer> numbers, Predicate<Integer> p) {
        int total = 0;
    
        for (int number : numbers) {
            if (p.test(number)) {
                total += number;
            }
        }
        return total;
    }
    

    Calling it like:

    sumAll(numbers, n -> n % 2 == 0);
    

    Source: DZone - Why We Need Lambda Expressions in Java

    0 讨论(0)
  • 2020-11-29 18:47

    Programming languages are not for machines to execute.

    They are for programmers to think in.

    Languages are a conversation with a compiler to turn our thoughts into something a machine can execute. One of the chief complaints about Java from people who come to it from other languages (or leave it for other languages) used to be that it forces a certain mental model on the programmer (i.e. everything is a class).

    I'm not going to weigh in on whether that's good or bad: everything is trade-offs. But Java 8 lambdas allow programmers to think in terms of functions, which is something you previously could not do in Java.

    It's the same thing as a procedural programmer learning to think in terms of classes when they come to Java: you see them gradually move from classes that are glorified structs and have 'helper' classes with a bunch of static methods and move on to something that more closely resembles a rational OO design (mea culpa).

    If you just think of them as a shorter way to express anonymous inner classes then you are probably not going to find them very impressive in the same way that the procedural programmer above probably didn't think classes were any great improvement.

    0 讨论(0)
  • 2020-11-29 18:51

    Lambda expressions do not change the set of problems you can solve with Java in general, but definitely make solving certain problems easier, just for the same reason we’re not programming in assembly language anymore. Removing redundant tasks from the programmer’s work makes life easier and allows to do things you wouldn’t even touch otherwise, just for the amount of code you would have to produce (manually).

    But lambda expressions are not just saving lines of code. Lambda expressions allow you to define functions, something for which you could use anonymous inner classes as a workaround before, that’s why you can replace anonymous inner classes in these cases, but not in general.

    Most notably, lambda expressions are defined independently to the functional interface they will be converted to, so there are no inherited members they could access, further, they can not access the instance of the type implementing the functional interface. Within a lambda expression, this and super have the same meaning as in the surrounding context, see also this answer. Also, you can not create new local variables shadowing local variables of the surrounding context. For the intended task of defining a function, this removes a lot of error sources, but it also implies that for other use cases, there might be anonymous inner classes which can not be converted to a lambda expression, even if implementing a functional interface.

    Further, the construct new Type() { … } guarantees to produce a new distinct instance (as new always does). Anonymous inner class instances always keep a reference to their outer instance if created in a non-static context. In contrast, lambda expressions only capture a reference to this when needed, i.e. if they access this or a non-static member. And they produce instances of an intentionally unspecified identity, which allows the implementation to decide at runtime whether to reuse existing instances (see also “Does a lambda expression create an object on the heap every time it's executed?”).

    These differences apply to your example. Your anonymous inner class construct will always produce a new instance, also it may capture a reference to the outer instance, whereas your (Developer o1, Developer o2) -> o1.getName().compareTo(o2.getName()) is a non-capturing lambda expression that will evaluate to a singleton in typical implementations. Further, it doesn’t produce a .class file on your hard drive.

    Given the differences regarding both, semantic and performance, lambda expressions may change the way programmers will solve certain problems in the future, of course, also due to the new APIs embracing ideas of functional programming utilizing the new language features. See also Java 8 lambda expression and first-class values.

    0 讨论(0)
  • 2020-11-29 18:52

    To answer your question, the matter of fact is lambdas don’t let you do anything that you couldn’t do prior to java-8, rather it enables you to write more concise code. The benefits of this, is that your code will be clearer and more flexible.

    0 讨论(0)
提交回复
热议问题