簡體   English   中英

在Java中的方法中將集合集合到集合中

[英]Unite Collection of Collections into Collection in a method in Java

我創建了一個Collection類,它擴展了ArrayList以添加一些有用的方法。 它看起來像這樣:

public class Collection<T> extends ArrayList<T> {
    //some methods...
}

我希望能夠將集合集合統一到一個集合中,如下所示:

{{1, 2}, {2,3}, {1}, {2}, {}} -> {1, 2, 2, 3, 1, 2}

我知道靜態方法應該如何:

public static<E> Collection<E> unite(Collection<Collection<E>> arr) {
    Collection<E> newCollection = new Collection<>();

    for(Collection<E> element : arr) {
        newCollection.merge(element);
    }

    return newCollection;
}

但我不知道如何使這個方法非靜態(所以它不接受任何參數,如下所示:

Collection<E> list = listOfLists.unite();

)。 這甚至可能嗎? 如果是的話,你能幫幫我嗎?

對任何具體類型的T來說都沒有意義。 如果T不是Collection類型,那么unite()是一個不相關的方法(例如,如果你有一個ArrayListModified<Double> ,你就不能展平它,因為那是荒謬的)。

所以你要么必須將T綁定到集合:

public class ArrayListModified<E, T extends Collection<E>> extends ArrayList<T> {

    public Collection<E> unite() {
        Collection<E> newCollection = new ArrayList<>();

        for (Collection<E> element : this) {
            newCollection.addAll(element);
        }

        return newCollection;
    }
}

或者使用一個靜態方法,它接受一個ArrayListModified<ArrayListModified<E>>參數,就像在當前實現中一樣(盡管它不需要是靜態的)。

一種方法是顯式地將類型參數聲明為List<E>然后它非常簡單:

class NestedList<E> extends ArrayList<List<E>> {
    public List<E> flatten() {
        return stream()
            .flatMap(Collection::stream)
            .collect(Collectors.toList());
    }
}

試試用'?' 而不是'E'。 Idk是否正確。

public Collection<?> unite(Collection<Collection<?>> collection) {
        Collection<?> newCollection = new Collection<>();

        for(Collection<?> element : collection) {
            newCollection.merge(element);
        }

        return newCollection;
    }

暫無
暫無

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

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