just curious on how to convert a 2d array into a 1d array.
只是好奇如何将2d数组转换为1d数组。
For example if my array was:
int[][] arr = {{2,3,4},
{5,6,7}};
lets say I wanted it just to be transferred to a 1d array such as:
int[] arr = {2,3,4,5,6,7};
2 个解决方案
#1
1
Assuming you're using Java 8+, you can create a Stream
of int[]
instances; then flatMapToInt
that to an IntStream
before converting it to an array. Which will do exactly as you describe. Like,
假设您使用的是Java 8+,您可以创建一个int []实例流;然后将flatMapToInt转换为IntStream,然后再将其转换为数组。这将完全按照您的描述进行。喜欢,
int[][] arr = { { 2, 3, 4 }, { 5, 6, 7 } };
int[] b = Stream.of(arr).flatMapToInt(IntStream::of).toArray();
System.out.println(Arrays.toString(b));
Which outputs
[2, 3, 4, 5, 6, 7]
#2
0
In Java 8 and integer array you can use:
在Java 8和整数数组中,您可以使用:
int[][] arr2d = new int[][] { { 1, 2, 3 }, { 4, 5 }, {6, 7} };
int[] arr1d = Arrays.stream(arr2d).flatMapToInt(Arrays::stream).toArray();
For Java 7 or object array:
对于Java 7或对象数组:
Object[][] obj2d = new Object[][] {};
List<Object> list = new ArrayList<>();
for (Object[] arr : obj2d) {
for (Object obj : arr) {
list.add(obj);
}
}
Object[] obj1d = list.toArray(new Object[] {});
#1
1
Assuming you're using Java 8+, you can create a Stream
of int[]
instances; then flatMapToInt
that to an IntStream
before converting it to an array. Which will do exactly as you describe. Like,
假设您使用的是Java 8+,您可以创建一个int []实例流;然后将flatMapToInt转换为IntStream,然后再将其转换为数组。这将完全按照您的描述进行。喜欢,
int[][] arr = { { 2, 3, 4 }, { 5, 6, 7 } };
int[] b = Stream.of(arr).flatMapToInt(IntStream::of).toArray();
System.out.println(Arrays.toString(b));
Which outputs
[2, 3, 4, 5, 6, 7]
#2
0
In Java 8 and integer array you can use:
在Java 8和整数数组中,您可以使用:
int[][] arr2d = new int[][] { { 1, 2, 3 }, { 4, 5 }, {6, 7} };
int[] arr1d = Arrays.stream(arr2d).flatMapToInt(Arrays::stream).toArray();
For Java 7 or object array:
对于Java 7或对象数组:
Object[][] obj2d = new Object[][] {};
List<Object> list = new ArrayList<>();
for (Object[] arr : obj2d) {
for (Object obj : arr) {
list.add(obj);
}
}
Object[] obj1d = list.toArray(new Object[] {});