Easy way to convert Iterable to Collection

前端 未结 19 2313
忘了有多久
忘了有多久 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:41

    You can use Eclipse Collections factories:

    Iterable iterable = Arrays.asList("1", "2", "3");
    
    MutableList list = Lists.mutable.withAll(iterable);
    MutableSet set = Sets.mutable.withAll(iterable);
    MutableSortedSet sortedSet = SortedSets.mutable.withAll(iterable);
    MutableBag bag = Bags.mutable.withAll(iterable);
    MutableSortedBag sortedBag = SortedBags.mutable.withAll(iterable);
    

    You can also convert the Iterable to a LazyIterable and use the converter methods or any of the other available APIs available.

    Iterable iterable = Arrays.asList("1", "2", "3");
    LazyIterable lazy = LazyIterate.adapt(iterable);
    
    MutableList list = lazy.toList();
    MutableSet set = lazy.toSet();
    MutableSortedSet sortedSet = lazy.toSortedSet();
    MutableBag bag = lazy.toBag();
    MutableSortedBag sortedBag = lazy.toSortedBag();
    

    All of the above Mutable types extend java.util.Collection.

    Note: I am a committer for Eclipse Collections.

提交回复
热议问题