Get size of an Iterable in Java

前端 未结 10 1214
半阙折子戏
半阙折子戏 2020-12-08 03:48

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 (i         


        
相关标签:
10条回答
  • 2020-12-08 04:14

    You can cast your iterable to a list then use .size() on it.

    Lists.newArrayList(iterable).size();
    

    For the sake of clarity, the above method will require the following import:

    import com.google.common.collect.Lists;
    
    0 讨论(0)
  • 2020-12-08 04:14

    I would go for it.next() for the simple reason that next() is guaranteed to be implemented, while remove() is an optional operation.

    E next()
    

    Returns the next element in the iteration.

    void remove()
    

    Removes from the underlying collection the last element returned by the iterator (optional operation).

    0 讨论(0)
  • 2020-12-08 04:17

    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.

    0 讨论(0)
  • 2020-12-08 04:21

    Instead of using loops and counting each element or using and third party library we can simply typecast the iterable in ArrayList and get its size.

    ((ArrayList) iterable).size();
    
    0 讨论(0)
提交回复
热议问题