将Java方法中的集合集合合并为一个集合

3
我创建了一个继承自ArrayList的Collection类,以添加一些有用的方法。它看起来像这样:

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

这种方式是否可行?如果可行的话,能否帮我一下?


名称“Collection”已被Java集合框架使用(用于所有集合的通用接口)。重新引入具有该名称的类将会使每个读者感到困惑,从而导致错误。我建议选择一个不同的名称。 - Zabuzard
请注意,您可以使用流式API的flatMap方法来实现。lists.stream().flatMap(List::stream).collect(Collectors.toList()); - Zabuzard
我希望能够以一种方法来实现它,这样链条会更美观。 - Nick
可以用 Kotlin 和扩展方法来实现,但我认为没有真正的“Java”方式来做到这一点。 - Lino
你认为调用应该长什么样?如果不使用参数,该方法如何知道两个列表?它只能知道当前的列表,如果它不是静态的,而不是第二个列表。list.unite(other)可能会有用。另外,我的流示例展示了如何实现这样一个方法。只需将所有列表打包到“lists”中。return List.of(firstList, secondList).stream().flatMap(List::stream).collect(Collectors.toList()); - Zabuzard
3个回答

2

对于任何具体类型 T 来说,这样做都没有意义。如果 T 不是一个 Collection 类型,则 unite() 方法是无关紧要的(例如,如果您有一个 ArrayListModified<Double>,则无法将其展平,因为这是荒谬的)。

因此,您必须将 T 限定为集合:

(Note: The original answer is not clear and may require more context to provide a better translation.)

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>>参数,就像您当前的实现一样(尽管它不需要是静态的)。 最初的回答。

0
一种方法是显式声明类型参数为 List<E>,然后就相当直接了:
class NestedList<E> extends ArrayList<List<E>> {
    public List<E> flatten() {
        return stream()
            .flatMap(Collection::stream)
            .collect(Collectors.toList());
    }
}

-1
尝试使用“?”代替“E”。我不知道我是否正确。
public Collection<?> unite(Collection<Collection<?>> collection) {
        Collection<?> newCollection = new Collection<>();

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

        return newCollection;
    }

我不想传递任何参数:Collection<T> collection = collectionOfCollections.unite() - Nick
1
如果你不确定你的答案是否能解决问题,最好不要写回答。 - Zabuzard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接