snippetjavaCritical
Easy way to convert Iterable to Collection
Viewed 0 times
iterableeasyconvertwaycollection
Problem
In my application I use 3rd party library (
Methods of this library return
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
Spring Data for MongoDB to be exact).Methods of this library return
Iterable, while the rest of my code expects Collection.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.Solution
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.Context
Stack Overflow Q#6416706, score: 408
Revisions (0)
No revisions yet.