java iterable,获取Java中Iterable的大小

这篇博客探讨了在Java中计算Iterable元素数量的两种方法,并建议使用Guava库的Iterables.size()方法,因为它既简洁又高效。博主通过基准测试发现两种方法在小规模数据上的性能差异不大,但提醒注意,第二种方法会清除Iterable的所有元素。此外,如果可能,应首先检查 Iterable 是否为 Collection 并直接调用 size() 方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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++;

}

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: Use the utility method Iterables.size(Iterable) of the great Guava library.

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.

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).

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...

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值