Easy way to change Iterable into Collection

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

Methods of this library return Iterable<T> , while the rest of my code expects Collection<T> .

Is there any utility method somewhere that will let me quickly convert one to the other. I would like to avoid making a banch of foreach loops in my code for such a simple thing.


With Guava you can use Lists.newArrayList(Iterable) or Sets.newHashSet(Iterable), among other similar methods. This will of course copy all the elements in to memory. If that isn't acceptable, I think your code that works with these ought to take Iterable rather than Collection . Guava also happens to provide convenient methods for doing things you can do on a Collection using an Iterable (such as Iterables.isEmpty(Iterable) or Iterables.contains(Iterable, Object) ), but the performance implications are more obvious.


In JDK 8, without depending on additional libs:

Iterator<T> source = ...;
List<T> target = new ArrayList<>();
source.forEachRemaining(target::add);

Edit: The above one is for Iterator . If you are dealing with Iterable ,

iterable.forEach(target::add);

您也可以为此编写自己的实用程序方法:

public static <E> Collection<E> makeCollection(Iterable<E> iter) {
    Collection<E> list = new ArrayList<E>();
    for (E item : iter) {
        list.add(item);
    }
    return list;
}
链接地址: http://www.djcxy.com/p/53888.html

上一篇: 在C#中有一个HashSet的AddRange等价物吗?

下一篇: 简单的方法将Iterable更改为Collection