我创建了一个继承自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();
这种方式是否可行?如果可行的话,能否帮我一下?
flatMap
方法来实现。lists.stream().flatMap(List::stream).collect(Collectors.toList());
- Zabuzardlist.unite(other)
可能会有用。另外,我的流示例展示了如何实现这样一个方法。只需将所有列表打包到“lists”中。return List.of(firstList, secondList).stream().flatMap(List::stream).collect(Collectors.toList());
- Zabuzard