java 如何在Java中将二维数组转换为一维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5466541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:15:22  来源:igfitidea点击:

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

javaarrays

提问by Jeel Shah

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 help me? Thanks.

我想知道如何将二维数组转换为一维数组。我想出了一些代码,但它似乎并不完全有效。有人可以帮帮我吗?谢谢。

public class TESTER1 {

    /**
     * @param args
     */

    static String[][] data = new String[][] {{"Dum","Dumer","Dumbest"}};

    public static void main(String[] args) {

        convertData(data);
    }

    public static void convertData(String[][]data) {
        String[] toReturn = new String[data.length];
        for(int i = 0;i<data.length;i++) {
            for(int j = 0;j<3;j++){
                toReturn[i] = data[i][j];
            }
        }
        for(String s:toReturn) {
            System.out.println(s);
        }
    }
}

[edit]Thank you very much. Is it possible to convert each row in the String[][] into a index in a String[] for example if we convert the String[][] (above code), then when i print out array[0] it should print out dum,dummer,dumbest [edit]

[编辑]非常感谢。是否可以将 String[][] 中的每一行转换为 String[] 中的索引,例如,如果我们转换 String[][](上面的代码),那么当我打印出 array[0] 时,它应该打印out dum,dummer,dumbest [编辑]

回答by pajton

public static String[] flatten(String[][] data) {
    ArrayList<String> list = new ArrayList<String>();

    for(int i = 0; i < data.length; i++) {
        for(int j = 0; j < data[i].length; j++){
            list.add(data[i][j]);
        }
    }

    return list.toArray(new String[0]);
}

Or add whole rows at one time:

或者一次添加整行:

    for(int i = 0; i < data.length; i++) {
        list.addAll( Arrays.asList(data[i]) );
    }

Edit:From comments on my answer it seems like this is what the OP wanted (i.e. converting each row of 2d array to some string representation of it):

编辑:从对我的回答的评论来看,这似乎是 OP 想要的(即将二维数组的每一行转换为它的一些字符串表示):

public static String[] rowsToString(String[][] data) {
    ArrayList<String> list = new ArrayList<String>();

    for(int i = 0; i < data.length; i++) {
        String row = Arrays.toString(data[i]);
        list.add( row.substring(1, row.length()-1) );
    }

    return list.toArray(new String[0]);
}

回答by Travis Webb

A cleaner version:

更干净的版本:

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

回答by joel.neely

The length of the 1-dimensional array must be the sums of the lengths of all rows in the 2-dimensional array. Of course, Java doesn't really have "true" 2-dimensional arrays, but arrays of arrays. This code works, and is wrapped in a simple demo program.

一维数组的长度必须是二维数组中所有行的长度之和。当然,Java 并没有真正“真正的”二维数组,而是数组的数组。此代码有效,并包含在一个简单的演示程序中。

public class ArrayFlattening {

公共类 ArrayFlattening {

public static final String[][] STRINGS2 = {
    {"my", "dog", "has", "fleas"},
    {"how", "now", "brown", "cow"},
    {"short", "row"},
    {"this", "is", "a", "final", "row", "in", "this", "test"},
};

public static String[] flatten(String[][] a2) {
    String[] result = new String[totalSize(a2)];
    int index = 0;
    for (String[] a1 : a2) {
        for (String s : a1) {
            result[index++] = s;
        }
    }
    return result;
}

public static int totalSize(String[][] a2) {
    int result = 0;
    for (String[] a1 : a2) {
        result += a1.length;
    }
    return result;
}

public static void main(String[] args) {
    System.out.println("" + STRINGS2.length + " rows");
    for (String[] strings1 : STRINGS2) {
        System.out.println("" + strings1.length + " strings");
        for (String s : strings1) {
            System.out.print("\t" + s);
        }
        System.out.println();
    }
    String[] strings1 = flatten(STRINGS2);
    System.out.println(strings1.length + " strings");
    for (String s : strings1) {
        System.out.print("\t" + s);
    }
    System.out.println();
}

}

}

回答by leo

Flatten did become much easier in Java 8 with the stream API. The function can be expressed as:

在 Java 8 中,有了流 API,Flatten 变得更容易了。该函数可以表示为:

private static String[] flatten(String[][] data) {
    return Stream.of(data).flatMap(Stream::of).toArray(String[]::new);
}