我有一个数组,例如
int[][] weights = {{1, 3, 2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, 1}};
Run Code Online (Sandbox Code Playgroud)
我需要从每个数组中获取{x, y, z}
两个数组{x, y, z}
和{y, x, z}
。像这样的东西
int[][] resultWeights = {{1, 3, 2}, {3, 1, 2}, {2, 1, 4}, {1, 2, 4} ...
Run Code Online (Sandbox Code Playgroud)
如何通过流来完成?
我需要从每个数组中获取
{x, y, z}
两个数组{x, y, z}
和{y, x, z}
。
迭代您的源并显式创建新条目:
int[][] weights = ...
// Every entry yields two
int[][] resultWeights = new int[weights.length * 2][];
// Iterate all entries
int i = 0;
for (int[] entry : weights) {
// Copy entry
resultWeights[i] = entry;
i++;
// Other version
resultWeights[i] = new int[] { entry[1], entry[0], entry[2] };
i++;
}
Run Code Online (Sandbox Code Playgroud)
请注意,您可以resultWeights[i++]
这样做。但对于一些程序员来说可能比较陌生。
正如您特别要求的流:
int[][] weights = ...
int[][] resultWeights = Arrays.stream(weights)
.flatMap(entry -> Stream.of(entry, new int[] { entry[1], entry[0], entry[2] }))
.toArray(int[][]::new);
Run Code Online (Sandbox Code Playgroud)