通过流转换数组数组

时间:2018-05-28 21:31:32

标签: java java-stream

我有一个数组,如

int[][] weights = {{1, 3, 2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, 1}};

我需要从每个数组{x, y, z}获取两个数组{x, y, z}{y, x, z}。像这样的东西

int[][] resultWeights = {{1, 3, 2}, {3, 1, 2}, {2, 1, 4}, {1, 2, 4} ... 

如何通过溪流完成?

2 个答案:

答案 0 :(得分:3)

  

我需要从每个数组{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++;
}

请注意,您可以改为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);

答案 1 :(得分:2)

每个条目flatMap只需{x, y, w}到数组流[{x, y, w}, {y, x, w}]。这样的事情应该有效:

Arrays.stream(weights)
  .flatMap(arr -> {
    int[] opp = new int[]{arr[1], arr[0], arr[2]};
    return Stream.of(arr, opp);
  })
  .toArray(i -> new int[i][]);

完整代码示例:

import java.util.stream.*;
import java.util.Arrays;

class SymmetrizeGraphMatrix {
  public static void main(String[] args) {
    int[][] weights = {{1, 3, 2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, 1}};
    int[][] result = Arrays.stream(weights)
      .flatMap(arr -> {
        int[] opp = new int[]{arr[1], arr[0], arr[2]};
        return Stream.of(arr, opp);
      })
      .toArray(i -> new int[i][]);

    for (int[] xyw : result) {
      System.out.println(Arrays.toString(xyw));
    }
  }
}

输出:

[1, 3, 2]
[3, 1, 2]
[2, 1, 4]
[1, 2, 4]
[2, 3, 3]
[3, 2, 3]
[3, 4, 2]
[4, 3, 2]
[4, 2, 1]
[2, 4, 1]