How can you convert a 2 dimensional array into a 1 dimensional array in Java

前端 未结 4 1188
伪装坚强ぢ
伪装坚强ぢ 2020-12-18 07:02

I would like to know how to convert a 2 dimensional array into a 1 dimensional array. I have come up with some code but it doesn\'t exactly seem to work. Can someone please

4条回答
  •  隐瞒了意图╮
    2020-12-18 07:36

    A cleaner version:

    public static String[] flatten(String[][] data) {
        List toReturn = new ArrayList();
        for (String[] sublist : Arrays.asList(data)) {
            for (String elem : sublist) {
                toReturn.add(elem);
            }
        }
        return toReturn.toArray(new String[0]);
    }
    

提交回复
热议问题