Easy way to convert Iterable to Collection

前端 未结 19 2318
忘了有多久
忘了有多久 2020-11-28 01:39

In my application I use 3rd party library (Spring Data for MongoDB to be exact).

Methods of this library return Iterable, while the rest of my

19条回答
  •  盖世英雄少女心
    2020-11-28 02:28

    While at it, do not forget that all collections are finite, while Iterable has no promises whatsoever. If something is Iterable you can get an Iterator and that is it.

    for (piece : sthIterable){
    ..........
    }
    

    will be expanded to:

    Iterator it = sthIterable.iterator();
    while (it.hasNext()){
        piece = it.next();
    ..........
    }
    

    it.hasNext() is not required to ever return false. Thus in the general case you cannot expect to be able to convert every Iterable to a Collection. For example you can iterate over all positive natural numbers, iterate over something with cycles in it that produces the same results over and over again, etc.

    Otherwise: Atrey's answer is quite fine.

提交回复
热议问题