[英]Flatmapping a 2D array by column rather than row in Java
给定以下二维数组
int[][] arr = {{1, 2}, {3, 4}, {5, 6}};
如何使用 Java 8 Stream API 逐列展平它? 我想得到:
int[] result = {1, 3, 5, 2, 4, 6};
我尝试做一个简单的 flatMap,但这会逐行展平并导致错误的顺序:
// result is { 1, 2, 3, 4, 5, 6 }
int[] result = Arrays.stream(arr)
.flatMapToInt(Arrays::stream)
.toArray();
我考虑首先转置数组以便我可以使用上面的代码片段,但是创建一个中间的、转置的数组副本似乎是不必要的。 如何直接按列平面图?
可以假设所有嵌套的 arrays 都是相同的长度。
您可以将内部索引和flatMap
流式传输到每个外部数组:
IntStream.range(0, arr[0].length)
.flatMap(i -> Arrays.stream(arr).mapToInt(a -> a[i]))
.toArray()
如果我们假设所有嵌套数组的长度相同,我们可以使用嵌套循环:
int[][] arr = {{1, 2}, {3, 4}, {5, 6}};
int[] res = new int[arr.length * arr[0].length];
int j = 0;
for (int i = 0; i < arr[0].length; i++) {
for (int[] a : arr) {
res[j++] = a[i];
}
}
System.out.println(Arrays.toString(res)); // [1, 3, 5, 2, 4, 6]
我修改了以前的代码,使其更加亲切和可读。
int[][] nestedArray = {{3, 4, 5, 6}, {1, 2}, {7, 8, 9}};
LinkedList<Integer> theList = new LinkedList<>();
for(int[] sList: nestedArray) {
stream(sList)
.forEach(theList::add);
}
theList.stream()
.forEach(e ->System.out.println(e));
这是另一种方法:
int[][] nestedArray = {{1, 12, 2}, {1, 13, 11, 5, 16}, {7, 8, 9}};
LinkedList<Integer> theList = new LinkedList<>();
for(int[] sList: nestedArray) {
stream(sList)
.forEach(theList::add);
}
theList.stream()
.forEach(e ->System.out.println(e));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.