Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the size of an Iterable Object? [duplicate]

Tags:

java

iterator

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.

like image 623
Sneha Parameswaran Avatar asked Jul 10 '12 11:07

Sneha Parameswaran


2 Answers

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;
}
like image 134
casablanca Avatar answered Oct 19 '22 20:10

casablanca


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.

like image 5
Safime Avatar answered Oct 19 '22 20:10

Safime