【问题标题】:Guava: Iterables.filter VS Collections2.filter, any big difference?Guava:Iterables.filter VS Collections2.filter,有什么大的区别吗?
【发布时间】:2012-05-31 13:26:16
【问题描述】:

我想知道在 Guava 中 Iterables.filter(Iterable, Predicate)Collections2.filter(Collection, Predicate) 方法之间是否有任何区别?

它们似乎既保持迭代顺序,又提供实时视图。 Javadoc 说调用Collections2.filter().size() 将遍历所有元素。

假设我有一个谓词来过滤项目列表,因此我想要视图中剩余的项目数(或列表,无关紧要)。我应该用什么? 使用Collections2.filter 似乎更简单,因为size() 方法由Collections 提供。

但是在后台,有没有区别:

ImmutableList.copyOf(
    Iterables.filter(lead.getActions(), isRealActionDoneByUserPredicate)
).size();

还有:

Collections2.filter(lead.getActions(),isRealActionDoneByUserPredicate).size();

顺便说一句,构建ImmutableList 是否比构建普通ArrayList 更快?

【问题讨论】:

  • 只是说明显而易见的事情:一个给你Iterable,另一个给你Collection。在Collections2.filter 下方使用FilteredCollection link 将许多事情委托给Iterables/Iterators,因此应该没有功能差异。例如@Louis Wasserman 的回答表明FilteredCollection#size() 正是Iterators.size(Iterators.filter(unfiltered.iterator(), predicate))

标签: java jakarta-ee guava


【解决方案1】:

Guava 贡献者在这里。

Collections2.filter(elements, predicate).size()

更可取,因为它不会复制——filter 方法都返回一个 view——但是

Iterables.size(Iterables.filter(elements, predicate))

本质上是等价的,并且无需任何复制即可找到答案。

至于构造ArrayListImmutableList的相对速度,因你使用哪种构造方法而异:

  • ImmutableList.copyOf(collection) 应该花费几乎完全相同的时间。 (它必须检查空值,但这很便宜。)
  • ImmutableList.builder()....build() 需要更长的小常数因子,因为它必须在 Builder 中使用 ArrayList,因为我们事先不知道将添加多少元素。
  • ImmutableList.of(...) 的速度大致相同。

也就是说,使用ImmutableList概念好处通常超过了较小的性能成本,尤其是在您经常传递列表的情况下。

【讨论】:

  • 谢谢。我想你的意思是 Iterables.size() 我没有找到任何 Iterables.length()
  • 切向,但是你们有没有考虑给Builders 一个构造函数,它采用int expectedSize (并暴露相应的builder(int) 方法?或者API 中增加的噪音会不会带来太少的好处?
  • 没关系,找到your debate about that
  • @LouisWasserman 为什么从“Guava 团队成员”变为“Guava 贡献者”?
  • 嗯,不管那天我是什么感觉。 (我在秋季开始在 Google 的团队中工作,但我已经贡献了将近两年的时间。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-17
  • 2015-08-24
  • 2012-11-22
  • 2020-07-24
  • 1970-01-01
  • 1970-01-01
  • 2011-05-23
相关资源
最近更新 更多