In my application I use 3rd party library (Spring Data for MongoDB to be exact).
Methods of this library return Iterable
, while the rest of my
Here's an SSCCE for a great way to do this in Java 8
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class IterableToCollection {
public interface CollectionFactory > {
U createCollection();
}
public static > U collect(Iterable iterable, CollectionFactory factory) {
U collection = factory.createCollection();
iterable.forEach(collection::add);
return collection;
}
public static void main(String[] args) {
Iterable iterable = IntStream.range(0, 5).boxed().collect(Collectors.toList());
ArrayList arrayList = collect(iterable, ArrayList::new);
HashSet hashSet = collect(iterable, HashSet::new);
LinkedList linkedList = collect(iterable, LinkedList::new);
}
}