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

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

问题描述

在我的应用程序中,我使用了 3rd 方库(准确地说是 Spring Data for MongoDB).

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

这个库的方法返回Iterable,而我的其余代码需要Collection.

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.

推荐答案

使用 Guava 你可以使用 Lists.newArrayList(Iterable)Sets.newHashSet(Iterable),以及其他类似的方法.这当然会将所有元素复制到内存中.如果这是不可接受的,我认为与这些一起使用的代码应该采用 Iterable 而不是 Collection.Guava 也恰好提供了方便的方法,可以使用 Iterable(例如 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天全站免登陆