获取Java中Iterable的大小 [英] Get size of an Iterable in Java

查看:185
本文介绍了获取Java中Iterable的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要弄清楚Java中Iterable中的元素数量. 我知道我可以做到:

I need to figure out the number of elements in an Iterable in Java. I know I can do this:

Iterable values = ...
it = values.iterator();
while (it.hasNext()) {
  it.next();
  sum++;
}

我也可以这样做,因为我不再需要Iterable中的对象:

I could also do something like this, because I do not need the objects in the Iterable any further:

it = values.iterator();
while (it.hasNext()) {
  it.remove();
  sum++;
}

小规模基准测试没有显示出太大的性能差异,对此问题没有任何评论或其他想法吗?

A small scale benchmark did not show much performance difference, any comments or other ideas for this problem?

推荐答案

TL; DR:使用实用程序方法 Guava 库.

TL;DR: Use the utility method Iterables.size(Iterable) of the great Guava library.

在您的两个代码段中,应该使用第一个,因为第二个将删除values中的所有元素,因此之后为空.为简单的查询(例如大小)更改数据结构是非常意外的.

Of your two code snippets, you should use the first one, because the second one will remove all elements from values, so it is empty afterwards. Changing a data structure for a simple query like its size is very unexpected.

为了提高性能,这取决于您的数据结构.例如,如果实际上是ArrayList,则从头开始删除元素(第二种方法正在做的事情)非常慢(计算大小变为O(n * n)而不是应有的O(n))

For performance, this depends on your data structure. If it is for example in fact an ArrayList, removing elements from the beginning (what your second method is doing) is very slow (calculating the size becomes O(n*n) instead of O(n) as it should be).

通常,如果values实际上是Collection而不是Iterable的可能性,请检查此情况并在以下情况下致电size():

In general, if there is the chance that values is actually a Collection and not only an Iterable, check this and call size() in case:

if (values instanceof Collection<?>) {
  return ((Collection<?>)values).size();
}
// use Iterator here...

size()的调用通常比计算元素数量要快得多,而这个技巧正是的docs/com/google/common/collect/Iterables.html#size(java.lang.Iterable)> Iterables.size(Iterable) 番石榴为您服务.

The call to size() will usually be much faster than counting the number of elements, and this trick is exactly what Iterables.size(Iterable) of Guava does for you.

这篇关于获取Java中Iterable的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆