gpt4 book ai didi

java-8 - 我应该使用 Stream API 进行简单迭代吗?

转载 作者:行者123 更新时间:2023-12-04 17:48:51 24 4
gpt4 key购买 nike

使用新的 Stream API 进行简单迭代有什么好处吗?

没有流 API:

 for (Map.Entry<String, String> entry : map.entrySet()) {
doSomething(entry);
}

使用流 API:
map.entrySet().stream().forEach((entry) -> {
doSomething(entry);
});

代码的长度和可读性大致相同。是否存在任何重要差异(例如性能)?

最佳答案

Streams API 使并行更容易实现(尽管您只会看到大型集合的好处)。如果您必须在第一个示例中实现并行性,那么代码量就会有相当大的差异(与将 .parallelStream() 添加到第二个示例相反)

根据 Java Trail on parallelism :

One difficulty in implementing parallelism in applications that use collections is that collections are not thread-safe, which means that multiple threads cannot manipulate a collection without introducing thread interference or memory consistency errors. The Collections Framework provides synchronization wrappers, which add automatic synchronization to an arbitrary collection, making it thread-safe. However, synchronization introduces thread contention. You want to avoid thread contention because it prevents threads from running in parallel. Aggregate operations and parallel streams enable you to implement parallelism with non-thread-safe collections provided that you do not modify the collection while you are operating on it. Note that parallelism is not automatically faster than performing operations serially, although it can be if you have enough data and processor cores. While aggregate operations enable you to more easily implement parallelism, it is still your responsibility to determine if your application is suitable for parallelism.

关于java-8 - 我应该使用 Stream API 进行简单迭代吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23265855/

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