Converting 2D array to 1D array in java can be achieved in various ways. Here we are going to discuss three ways using for loop, enhanced for loop, and Java 8 syntax.
Using for loop
Iterate the 2D array and convert it to a 1D array using the for loop. This loop is used in the earlier versions of Java from version 1 to 4.
public static List<Integer> oneDArray(int[][] array) {
List<Integer> oneDimensionalArray = new ArrayList<>();
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++)
oneDimensionalArray.add(array[row][col]);
}
return oneDimensionalArray;
}
Using JDK 5 Enhanced for loop
Iterate over the array using Java 1.5 enhanced for loop and add each integer value to the List. Return the List to print it in the console.
public static List<Integer> flattenArray(int[][] array) {
List<Integer> oneDimensionalArray = new ArrayList<>();
for (int[] row : array) {
for (int col : row) {
// flattened 1D array
oneDimensionalArray.add(col);
}
}
return oneDimensionalArray;
}
Using Java 8
In Java 8 use the Stream.of or the Arrays.stream to pass the 2d array input and convert it into an IntStream with flatMapToInt operation. The IntStream is converted to an array.
public static int[] flattenArrayJDK8(int[][] array) {
// flattened 1D array
int[] intArray = Stream.of(array).
flatMapToInt(IntStream::of).toArray();
return intArray;
}
Here is the complete code
package com.digitizedpost.array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class ArrayConversion {
public static void main(String[] args) {
// 2d array input
int[][] input = {
{3, 2, 7},
{12, 2, 6},
{4, 3, 0},
{7, 3, 1}
};
Arrays.stream(flattenArrayJDK8(input)).
forEach(i -> System.out.print(i + " "));
flattenArray(input).stream().
forEach(i -> System.out.print(i + " "));
oneDArray(input).stream().
forEach(i -> System.out.print(i + " "));
}
public static List<Integer> flattenArray(int[][] array) {
List<Integer> oneDimensionalArray = new ArrayList<>();
for (int[] row : array) {
for (int col : row) {
// flattened 1D array
oneDimensionalArray.add(col);
}
}
return oneDimensionalArray;
}
public static int[] flattenArrayJDK8(int[][] array) {
// flattened 1D array
int[] intArray = Stream.of(array).
flatMapToInt(IntStream::of).toArray();
return intArray;
}
public static List<Integer> oneDArray(int[][] array) {
List<Integer> oneDimensionalArray = new ArrayList<>();
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++)
oneDimensionalArray.add(array[row][col]);
}
return oneDimensionalArray;
}
}
Output
The output of the flattened array will be displayed like below
3 2 7 12 2 6 4 3 0 7 3 1