Easy way to convert Iterable to Collection

前端 未结 19 2274
忘了有多久
忘了有多久 2020-11-28 01:39

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

19条回答
  •  失恋的感觉
    2020-11-28 02:34

    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.

提交回复
热议问题