简单的方法来改变Iterable到集合 [英] Easy way to change Iterable into Collection

查看:125
本文介绍了简单的方法来改变Iterable到集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我使用第三方库(Spring Data for MongoDb)。



这个库返回的方法 Iterable< T > ,而我的代码的其余部分预期 Collection< T>



有任何实用的方法,在某处,将让我迅速转换到另一个。我想避免在我的代码中创建一个 foreach 循环。

解决方案

使用 Guava ,您可以使用 Lists.newArrayList(Iterable) Sets.newHashSet(Iterable),以及其他类似的方法。这当然会将所有元素复制到内存中。如果这是不可接受的,我认为你的代码与这些工作应该 Iterable 而不是集合。 Guava也恰巧提供了方便的方法来处理你可以在 Collection 上使用 Iterable (例如 Iterables.isEmpty(Iterable) Iterables.contains(Iterable,Object)),但性能影响更明显。 / p>

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.

这篇关于简单的方法来改变Iterable到集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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