将Iterable转换为Collection的简便方法 [英] Easy way to convert Iterable to Collection

查看:82
本文介绍了将Iterable转换为Collection的简便方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我使用第三方库(确切地说就是MongoDB的Spring数据)。

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

此库的方法返回 Iterable< T> ; ,而我的其余代码需要 Collection< T>

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

是有什么实用方法可以让我快速将一个转换为另一个吗?我想避免在我的代码中为这么简单的事情创建一堆 foreach 循环。

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

推荐答案

使用番石榴,你可以使用 Lists.newArrayList(Iterable) Sets.newHashSet(Iterable),以及其他类似的方法。这当然会将所有元素复制到内存中。如果这是不可接受的,我认为你的代码应该采用 Iterable 而不是 Collection 。 Guava还提供了方便的方法,可以使用 Iterable Collection 上执行操作(例如 Iterables.isEmpty(Iterable) Iterables.contains(Iterable,Object)),但性能影响更明显。

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.

这篇关于将Iterable转换为Collection的简便方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆