简体   繁体   English

给定集合名称(ArrayList、LinkedList 等)和集合中的项目,如何创建任何集合?

[英]How do I create any Collection given the collection name(ArrayList, LinkedList etc) and items in the collection?

I am trying to create a method that accepts the type of collection and the type of items inside the collection.我正在尝试创建一个接受集合类型和集合内项目类型的方法。

ArrayList<Integer> ints = getCollection(ArrayList.class, Integer.class);

How do I write the getCollection so that, given any Collection subclass and any Number subclass, the method should create a collection and populate it with random elements of Number or subtype of Number?如何编写getCollection以便在给定任何 Collection 子类和任何 Number 子类的情况下,该方法应该创建一个集合并用 Number 的随机元素或 Number 的子类型填充它?

If you can, it would be better to pass in a Supplier for the collection, and a Function to convert from Number to the sub-type, such as:如果可以的话,最好为集合传入一个 Supplier ,并传入一个 Function 以从 Number 转换为子类型,例如:

    private static final SecureRandom RND = new SecureRandom();
    private static final int COUNT_MAX = 100;

    public static void main(String[] args) {
        ArrayList<Integer> ints = getCollection(ArrayList::new, Number::intValue);
        System.out.println(ints);
        Set<Double> doubles = getCollection(HashSet::new, Number::doubleValue);
        System.out.println(doubles);
    }

    private static <T extends Collection<U>, U extends Number> T getCollection(
        Supplier<T> supplier, Function<Number, U> fn) {
        T collection = supplier.get();
        int count = RND.nextInt(COUNT_MAX);
        for (int i = 0; i < count; i++)
            collection.add(fn.apply(RND.nextInt()));
        return collection;
    }

This way, you won't need any casting.这样,您将不需要任何铸造。

Update using streams:使用流更新

    private static <T extends Collection<U>, U extends Number> T getCollection(
        Supplier<T> supplier, Function<Number, U> fn) {
        int count = RND.nextInt(COUNT_MAX);
        return RND.ints().limit(count).boxed().map(fn)
            .collect(Collectors.toCollection(supplier));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM