Get size of an Iterable in Java

前端 未结 10 1247
半阙折子戏
半阙折子戏 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;
    

提交回复
热议问题