Easy way to convert Iterable to Collection

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

    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);
        }
    }
    

提交回复
热议问题