gpt4 book ai didi

java - 为什么在 Java 中使用 lambda 表达式?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:58 26 4
gpt4 key购买 nike

我知道使用 lambda 表达式 (LE) 我们可以节省几行代码,比如为功能接口(interface)创建对象。 LE 也将更具可读性。但我确信这不是提供此功能的主要原因。我在 google 上搜索 Why Lambda expression in java 我在这个 article 找到了这个有趣的引用

Prior to Java 8, processing the elements of any collection could be done by obtaining an iterator from the collection and then iterating over the elements and then processing each element. If the requirement is to process the elements in parallel, it would be done by the client code. With the introduction of Stream API in Java 8, functions can be passed to collection methods and now it is the responsibility of collection to process the elements either in a sequential or parallel manner. -

对我来说,这看起来像是流式 api 而非 LE 的优势。即使没有提供 LE,开发人员也可以实现相同的目标创建匿名消费者类。我在这里看到的支持 LE 的唯一优势是开发人员不必记住哪个对象需要创建功能接口(interface)。所以它把 java 带向函数式编程,开发人员说应用这个函数,他不在乎关于对象(让 jvm 处理这个)。

这是 LE 的主要优势还是还有比这更重要的优势?

更新:-

我尝试了下面的简单程序,其中我尝试使用 lambda 表达式来衡量并行处理的性能。发现并行处理需要 84 个时间单位,而顺序处理只需要 4 个时间单位。是不是因为程序不够大,线程开销也可能在这里发挥作用?可能是在更大的函数中可以看到优势?

public class Java8Tester {

final static String salutation = "Hello! ";

public static void main(String args[]){
List<String> stringList = new ArrayList<String>();


for(int i=0;i <100;i++){
stringList.add("Hello1");
stringList.add("Hello2");
}

long startTime = System.currentTimeMillis();
System.out.println(startTime);
stringList.parallelStream().forEach((string) -> {System.out.println("content is " + string);
});
long stopTime = System.currentTimeMillis();
System.out.println(stopTime);
System.out.println("time taken in parallel processing" + (stopTime - startTime)); // took 84 units of time


startTime = System.currentTimeMillis();
System.out.println(startTime);

for(String str : stringList ) {
System.out.println("content is " + str);
}

stopTime = System.currentTimeMillis();
System.out.println(stopTime);
System.out.println("time taken in sequential processing" + (stopTime - startTime)); // // took 4 units of time
}


}

最佳答案

我不认为 lambda 表达式有一个主要目的,而是许多小的附加好处,它们共同产生了巨大的影响。

  • Lambda 删除了大量样板代码。

  • 它们使代码更短且更易于阅读。

  • 减少对匿名内部类的需求。

  • 允许更多的代码重用。

任何更多功能。

我最喜欢的 lambda 优点之一是能够创建默认接口(interface)方法。一些我认为我现在不能没有的东西。

所以 lambda 没有一个特定的存在理由。它们为更多函数式编程打开了大门,让 Java 得以发展,并总体上使编码变得更加有趣。

关于java - 为什么在 Java 中使用 lambda 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33718482/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com