简单的方法将Iterable更改为Collection
在我的应用程序中,我使用第三方库(准确地说,Spring Data for MongoDb)。
这个库的方法返回Iterable<T> ,而我的其他代码需要Collection<T> 。
有什么实用方法可以让我快速将一个转换为另一个。 我想避免在我的代码中使用foreach循环来实现这样一个简单的事情。
使用番石榴,您可以使用Lists.newArrayList(Iterable)或Sets.newHashSet(Iterable)等方法。 这当然会将所有元素复制到内存中。 如果这是不可接受的,我认为你的代码应该采用Iterable而不是Collection 。 番石榴也碰巧提供了方便的方法来处理你使用Iterable (例如Iterables.isEmpty(Iterable)或Iterables.contains(Iterable, Object) )可以对Collection进行的操作,但性能影响更为明显。
在JDK 8中,不依赖于其他库:
Iterator<T> source = ...;
List<T> target = new ArrayList<>();
source.forEachRemaining(target::add);
编辑:上面的一个是Iterator 。 如果你正在处理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/53887.html
上一篇: Easy way to change Iterable into Collection
下一篇: Why is my namespace not recognized in Visual Studio / xaml
