簡體   English   中英

在Java中轉換通用Collection的類型

[英]Converting the type of a generic Collection in Java

在我的代碼中的幾個地方,我有ArrayLists和TreeSets我希望轉換其通用類型。 因此,例如,我有一個ArrayList<Integer> ,我希望將其轉換為ArrayList<Long> 或者我有一個TreeSet<BigInteger> ,我希望將其轉換為TreeSet<String>

可以進行所有這些轉換,但是隨后我必須為每種類型轉換創建一個不同的函數。 因此,我想創建一個通用函數,其簽名如下所示:

public static <Q,T> Collection<Q> convert(Collection<T> col, Class<Q> Q)

我想要的是從col (例如ArrayList )獲取類,創建該類和Q類型的新集合(稱為newCol ),然后遍歷col並將每個T類型的元素轉換為Q類型並添加它到newCol ,最后返回newCol

我怎樣才能做到這一點?

沒有像Java中強制轉換不兼容類這樣的特殊機制。 您需要指定一個顯式函數來執行轉換。 使用Java 8確實很容易:

public static <Q,T,C extends Collection<Q>> C convert(Collection<T> col, Function<T, Q> fn, 
                   Supplier<C> supplier) {
    return col.stream().map(fn).collect(Collectors.toCollection(supplier));
}

像這樣使用它:

TreeSet<BigInteger> values = // fill them somehow
TreeSet<String> converted = convert(values, BigInteger::toString, TreeSet::new);

@Tagir Valeev是正確的。 您可以在Java 8中輕松完成此操作。但是,如果您使用Java 7,則可以嘗試執行以下操作:

    public static <F, T> Collection<T> transform(Collection<F> fromCollection, Function<? super F, T> function) {
        return new TransformedCollection<F, T>(fromCollection, function);
    }

    static class TransformedCollection<F, T> extends AbstractCollection<T> {
        final Collection<F> fromCollection;
        final Function<? super F, ? extends T> function;

        TransformedCollection(Collection<F> fromCollection, Function<? super F, ? extends T> function) {
            this.fromCollection = checkNotNull(fromCollection);
            this.function = checkNotNull(function);
        }

        @Override public void clear() {
            fromCollection.clear();
        }

        @Override public boolean isEmpty() {
            return fromCollection.isEmpty();
        }

        @Override public Iterator<T> iterator() {
            return Iterators.transform(fromCollection.iterator(), function);
        }

        @Override public int size() {
            return fromCollection.size();
        }
    }

它是Guava庫中的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM