簡體   English   中英

給定集合名稱(ArrayList、LinkedList 等)和集合中的項目,如何創建任何集合?

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

我正在嘗試創建一個接受集合類型和集合內項目類型的方法。

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

如何編寫getCollection以便在給定任何 Collection 子類和任何 Number 子類的情況下,該方法應該創建一個集合並用 Number 的隨機元素或 Number 的子類型填充它?

如果可以的話,最好為集合傳入一個 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;
    }

這樣,您將不需要任何鑄造。

使用流更新

    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