How to find the size of the Iterable object?

I am writing MR Job. But I'm stuck in a problem related to an Iterable object. I need to find its size. I applied it to the List object, but that was wrong. (The list can be passed to Iterable, but it cannot make a U-turn.) There is another way, for example, using Iterator for an object and increasing the counter for each value. But this is not an optimal solution. Can anyone suggest a better way?

Please help me. Thanks in advance.

+7
source share
3 answers

The Collection interface provides the size() method, and it extends Iterable . If your iterator comes from a collection, you can set its size, otherwise you are out of luck, you just need to continue the iteration to the end.

Here is the 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; } 
+15
source

You need to go through the iterator and count the elements. For example,

  while (iterator.hasNext()) { iterator.next(); count++; } 

This is not very clean, but the iterator is used to iterate and does not provide any specific api for this.

But where is the iterator created? If this comes from another object, such as a Collection object, you can determine the size of the source, not the iterator itself.

+5
source

An iterator does not have size () on it, but some of the Collections from which Iterator was derived have size (), for example java.util.LinkedList.size (). Thus, you may need to iterate in some cases.

0
source

All Articles