可以使用递归来解决这个问题,对于每个元素,如果是列表,则递归调用函数,否则将其添加到结果列表中。

Java代码:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Object> input = new ArrayList<>();
        input.add(new ArrayList<Integer>() {{
            add(1);
            add(2);
            add(3);
        }});
        input.add(new ArrayList<Integer>() {{
            add(4);
            add(5);
            add(new ArrayList<Integer>() {{
                add(6);
                add(7);
            }});
            add(8);
        }});
        input.add(new ArrayList<Integer>() {{
            add(9);
            add(new ArrayList<Integer>() {{
                add(10);
                add(11);
                add(new ArrayList<Integer>() {{
                    add(12);
                    add(13);
                    add(14);
                }});
            }});
        }});

        List<Integer> result = getInnerList(input);
        System.out.println(result);
    }

    private static List<Integer> getInnerList(List<Object> input) {
        List<Integer> result = new ArrayList<>();
        for (Object obj : input) {
            if (obj instanceof List) {
                result.addAll(getInnerList((List<Object>) obj));
            } else if (obj instanceof Integer) {
                result.add((Integer) obj);
            }
        }
        return result;
    }
}

输出:

[1, 2, 3, 6, 7, 5, 8, 10, 11, 12, 13, 14, 9]
比如说给一个这样的字符串 1 2 3 4 5 6 7 8 9 10 11 12 13 14 要求取最里面的一层的list的所有数据并且不能用String的方法用java写注意list层数是变化的

原文地址: https://www.cveoy.top/t/topic/br6C 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录