我有一个多维char数组:
board = new char[3][3];
Run Code Online (Sandbox Code Playgroud)
在我的一个课程中代表一个tic tac toe游戏,我已经初步化了.
什么是将其压平成一个阵列的最佳方法?
int[][] x = { { 1, 2 }, { 3, 4 } };
int [] flatten = Arrays.stream(x)
.flatMapToInt(Arrays::stream)
.toArray();
Run Code Online (Sandbox Code Playgroud)
使用stream api这很简单.
如果您使用的是char [][]:
char[][] board = {
{ 'x', 'o', ' ' },
{ ' ', 'o', 'x' },
{ ' ', 'o', 'x' },
};
StringBuilder sb = Arrays.stream(board)
.flatMapToInt(x -> IntStream.range(0, x.length).map(i -> x[i]))
.mapToObj(x -> (char) x)
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append);
char[] chars = new char[sb.length()];
sb.getChars(0, sb.length(), chars, 0);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |