将2d数组转换为1d数组

时间:2017-11-17 02:34:30

标签: java arrays

只是好奇如何将2d数组转换为1d数组。

For example if my array was:

int[][] arr = {{2,3,4},
               {5,6,7}};

lets say I wanted it just to be transferred to a 1d array such as:

int[] arr = {2,3,4,5,6,7};

2 个答案:

答案 0 :(得分:1)

假设您使用的是Java 8+,则可以创建Streamint[]实例;然后flatMapToIntIntStream转换为数组之前的dep。这将完全按照您的描述进行。像,

int[][] arr = { { 2, 3, 4 }, { 5, 6, 7 } };
int[] b = Stream.of(arr).flatMapToInt(IntStream::of).toArray();
System.out.println(Arrays.toString(b));

哪个输出

[2, 3, 4, 5, 6, 7]

答案 1 :(得分:0)

在Java 8和整数数组中,您可以使用:

int[][] arr2d = new int[][] { { 1, 2, 3 }, { 4, 5 }, {6, 7} };
int[] arr1d = Arrays.stream(arr2d).flatMapToInt(Arrays::stream).toArray();

对于Java 7或对象数组:

Object[][] obj2d = new Object[][] {};

List<Object> list = new ArrayList<>();
for (Object[] arr : obj2d) {
    for (Object obj : arr) {
        list.add(obj);
    }
}

Object[] obj1d = list.toArray(new Object[] {});