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
I use my custom utility to cast an existing Collection if available.
Main:
public static Collection toCollection(Iterable iterable) {
if (iterable instanceof Collection) {
return (Collection) iterable;
} else {
return Lists.newArrayList(iterable);
}
}
Ideally the above would use ImmutableList, but ImmutableCollection does not allow nulls which may provide undesirable results.
Tests:
@Test
public void testToCollectionAlreadyCollection() {
ArrayList list = Lists.newArrayList(FIRST, MIDDLE, LAST);
assertSame("no need to change, just cast", list, toCollection(list));
}
@Test
public void testIterableToCollection() {
final ArrayList expected = Lists.newArrayList(FIRST, null, MIDDLE, LAST);
Collection collection = toCollection(new Iterable() {
@Override
public Iterator iterator() {
return expected.iterator();
}
});
assertNotSame("a new list must have been created", expected, collection);
assertTrue(expected + " != " + collection, CollectionUtils.isEqualCollection(expected, collection));
}
I implement similar utilities for all subtypes of Collections (Set,List,etc). I'd think these would already be part of Guava, but I haven't found it.