I'm in process of writing an MR Job. But I'm stuck with an Issue related to an Iterable object. I need to find its size. I casted it to a List object,but that was wrong.(List can be casted to Iterable, but cannot do reversal.) There is another way, i.e. by using an Iterator for the object and incrementing a counter for each value. But that is not an optimal solution. Can anybody suggest a better way?.
Please help me. Thanks in advance.
The Collection
interface provides a size()
method and it extends Iterable
. If your iterator happens to come from a collection, you can ask it for its size, otherwise you are out of luck, you simply have to iterate till the end.
Here's a hack that implements this:
public int size(Iterable<?> it) {
if (it instanceof Collection)
return ((Collection<?>)it).size();
// else iterate
int i = 0;
for (Object obj : it) i++;
return i;
}
You have to go through the iterator and count the items. For instance,
while (iterator.hasNext()) {
iterator.next();
count++;
}
This is not very clean but iterator is used with the purpose of iterate and does not provide any specific api for that.
But, where is the iterator created? If it comes from another object, for instance a Collection object, you can determine the size of the source and not the iterator itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With