[英]How to convert a two dimensional int array to a single string using streams?
I'm trying to convert a two dimensional int array to a single int where there is a space in between each number and a line break after each single array using streams. 我正在尝试将二维int数组转换为单个int,其中每个数字和每个使用流的单个数组之后的换行符之间都有一个空格。
I've done this easily for single dimensional arrays with mapToObj, but this does not when the stream consists of arrays instead of ints. 我已经使用mapToObj轻松地对一维数组完成了此操作,但是当流是由数组而不是int组成时,这不是很容易。
int[] a = {1, 2, 3, 4};
String[] strArray = Arrays.stream(a).mapToObj(String::valueOf).toArray(String[]::new);
String joined = String.join(" ", strArray);
a
would map to 1 2 3 4
here. a
将在此处映射到1 2 3 4
。 What I want would be to have something like 我想要的是像
int[][] a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
map to 映射到
1 2 3
4 5 6
7 8 9
How can I get something similar to joined
, but with two dimensional arrays and still using streams? 我怎样才能得到类似的东西
joined
,但随着二维数组,仍然使用流?
You can use something like this : 您可以使用如下所示的内容:
String output = Arrays.stream(a)
.map(ints -> IntStream.of(ints).mapToObj(String::valueOf).collect(Collectors.joining(" ")))
.collect(Collectors.joining("\n"));
The output will be : 输出将是:
1 2 3
4 5 6
7 8 9
First we map every integer array to a String which consists of integers separated by space and then we collect those Strings joining them with "\\n". 首先,我们将每个整数数组映射到一个由空格分隔的整数组成的字符串,然后收集那些以“ \\ n”连接的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.