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

后端 未结 9 1547
我寻月下人不归
我寻月下人不归 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条回答
  •  猫巷女王i
    2020-11-29 18:59

    Saving lines of code can be viewed as a new feature, if it enables you to write a substantial chunk of logic in a shorter and clearer manner, which takes less time for others to read and understand.

    Without lambda expressions (and/or method references) Stream pipelines would have been much less readable.

    Think, for example, how the following Stream pipeline would have looked like if you replaced each lambda expression with an anonymous class instance.

    List names =
        people.stream()
              .filter(p -> p.getAge() > 21)
              .map(p -> p.getName())
              .sorted((n1,n2) -> n1.compareToIgnoreCase(n2))
              .collect(Collectors.toList());
    

    It would be:

    List names =
        people.stream()
              .filter(new Predicate() {
                  @Override
                  public boolean test(Person p) {
                      return p.getAge() > 21;
                  }
              })
              .map(new Function() {
                  @Override
                  public String apply(Person p) {
                      return p.getName();
                  }
              })
              .sorted(new Comparator() {
                  @Override
                  public int compare(String n1, String n2) {
                      return n1.compareToIgnoreCase(n2);
                  }
              })
              .collect(Collectors.toList());
    

    This is much harder to write than the version with lambda expressions, and it's much more error prone. It's also harder to understand.

    And this is a relatively short pipeline.

    To make this readable without lambda expressions and method references, you would have had to define variables that hold the various functional interface instances being used here, which would have split the logic of the pipeline, making it harder to understand.

提交回复
热议问题