Guava:Iterables.filter VS Collections2.filter,有什么大不同?

Seb*_*ber 17 java java-ee 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();
Run Code Online (Sandbox Code Playgroud)

和:

Collections2.filter(lead.getActions(),isRealActionDoneByUserPredicate).size();
Run Code Online (Sandbox Code Playgroud)

顺便说一句,建设ImmutableList比建设正常更快ArrayList?

Lou*_*man 23

番石榴贡献者在这里.

Collections2.filter(elements, predicate).size()
Run Code Online (Sandbox Code Playgroud)

是优选的,因为它没有复制 - 两种filter方法都返回一个视图 - 但是

Iterables.size(Iterables.filter(elements, predicate))
Run Code Online (Sandbox Code Playgroud)

本质上是等价的,并且在没有任何复制的情况下也会找到答案.

至于构造a ArrayList与a 的相对速度ImmutableList,它取决于你使用的构造方法:

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

也就是说,使用的概念上的好处ImmutableList往往超过了小的性能成本,特别是如果你经常传递列表.