Java ArrayList:合并 ArrayLists 中的 ArrayLists 以创建一个 ArrayList [英] Java ArrayList: Merging ArrayLists within ArrayLists to create one ArrayList

查看:25
本文介绍了Java ArrayList:合并 ArrayLists 中的 ArrayLists 以创建一个 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,但似乎找不到执行以下操作的 API 调用:我需要将 ArrayList 中的所有 ArrayList 合并以形成一个 ArrayList,其中包含来自所有子 ArrayList 的所有元素,如果那样的话有道理.

I've looked around but I can't seem to find an API call that does the following: I need to merge all ArrayLists in an ArrayList to form one ArrayList with all the elements from all the sub-ArrayLists, if that makes sense.

这是一个例子:

{"It's", "a", {"small", "world, "after"}, {"all"}} 变成 {"It's", "a", "small", "world", "之后", "所有"}

{"It's", "a", {"small", "world, "after"}, {"all"}} becomes {"It's", "a", "small", "world", "after", "all"}

推荐答案

public List<?> flatten(List<?> input) {
    List<Object> result = new ArrayList<Object>();

    for (Object o: input) {
        if (o instanceof List<?>) {
            result.addAll(flatten((List<?>) o));
        } else {
            result.add(o);
        }
    }

    return result;
}

这篇关于Java ArrayList:合并 ArrayLists 中的 ArrayLists 以创建一个 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆