Get size of an Iterable in Java

前端 未结 10 1213
半阙折子戏
半阙折子戏 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:01

    As for me, these are just different methods. The first one leaves the object you're iterating on unchanged, while the seconds leaves it empty. The question is what do you want to do. The complexity of removing is based on implementation of your iterable object. If you're using Collections - just obtain the size like was proposed by Kazekage Gaara - its usually the best approach performance wise.

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

    Strictly speaking, Iterable does not have size. Think data structure like a cycle.

    And think about following Iterable instance, No size:

        new Iterable(){
    
            @Override public Iterator iterator() {
                return new Iterator(){
    
                    @Override
                    public boolean hasNext() {
                        return isExternalSystemAvailble();
                    }
    
                    @Override
                    public Object next() {
                        return fetchDataFromExternalSystem();
                    }};
            }};
    
    0 讨论(0)
  • 2020-12-08 04:03

    java 8 and above

    StreamSupport.stream(data.spliterator(), false).count();
    
    0 讨论(0)
  • 2020-12-08 04:06

    If you are working with java 8 you may use:

    Iterable values = ...
    long size = values.spliterator().getExactSizeIfKnown();
    

    it will only work if the iterable source has a determined size. Most Spliterators for Collections will, but you may have issues if it comes from a HashSetor ResultSetfor instance.

    You can check the javadoc here.

    If Java 8 is not an option, or if you don't know where the iterable comes from, you can use the same approach as guava:

      if (iterable instanceof Collection) {
            return ((Collection<?>) iterable).size();
        } else {
            int count = 0;
            Iterator iterator = iterable.iterator();
            while(iterator.hasNext()) {
                iterator.next();
                count++;
            }
            return count;
        }
    
    0 讨论(0)
  • 2020-12-08 04:06

    Why don't you simply use the size() method on your Collection to get the number of elements?

    Iterator is just meant to iterate,nothing else.

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

    This is perhaps a bit late, but may help someone. I come across similar issue with Iterable in my codebase and solution was to use for each without explicitly calling values.iterator();.

    int size = 0;
    for(T value : values) {
       size++;
    }
    
    0 讨论(0)
提交回复
热议问题