gpt4 book ai didi

java - FluentIterable : should limit() be called as soon as possible?

转载 作者:行者123 更新时间:2023-11-29 08:35:38 26 4
gpt4 key购买 nike

我正在查看 Guava 的 FluentIterable 的 javadoc 和网络上的大量示例,他们倾向于将 limit() 放在 filter() 和 transform() 之后,这表明所有元素都在 Iterable 被截断为第一个 N。这是他们页面中的示例。

   List<String> results =
FluentIterable.from(database.getClientList())
.filter(activeInLastMonthPredicate)
.transform(Functions.toStringFunction())
.limit(10)
.toList();

这看起来效率很低。我错过了什么吗?为什么会出现这种模式?不应该是下面的吗?

   List<String> results =
FluentIterable.from(database.getClientList())
.filter(activeInLastMonthPredicate)
.limit(10)
.transform(Functions.toStringFunction())
.toList();

最佳答案

FluentIterable (和 Guava 的非流利 IterablesIterators )是 lazy , 这意味着

Unless otherwise noted, all of the iterables produced in this class are lazy, which means that their iterators only advance the backing iteration when absolutely necessary.

这可能在 JDK 8 的 Stream documentation 中有更好的解释:

Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.

还有Stream#limit(int) documentation :

Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.

This is a short-circuiting stateful intermediate operation.

(强调我的。)

因此,放置 .limit(10) 的位置没有区别 - 在您的两个示例中,最多只会消耗 10 个元素。您可以通过将 Functions.toStringFunction() 更改为您可以检查的内容来检查它在每种情况下最多被调用 10 次。

关于java - FluentIterable : should limit() be called as soon as possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44304144/

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