Home > Software design >  Flattening an Array in Java
Flattening an Array in Java

Time:11-17

How can I flatten this array, that I've declared at the top of the class but not inside a method, into a single string inside a method?

private int[][]     numbers;

CodePudding user response:

I took the 2d array and put them in a string, and this is how I did it :-) Output:325325

    public static void main(String[] args) {
    int[][]  numbers =  {{3, 2, 5},
                        {3, 2, 5}};

    StringBuilder myString = new StringBuilder();
    for(int i = 0; i < numbers.length; i  ) {
        for(int j = 0; j < numbers[i].length; j  ) {
            myString.append(numbers[i][j]);
        }
    }

    System.out.println(myString);
}

CodePudding user response:

Try this:

int[] flattened = Arrays.stream(numbers).flatMapToInt(Arrays::stream).toArray();

Or to flatten to a String:

String str = Arrays.stream(numbers).flatMapToInt(Arrays::stream)
  .mapToObj(String::valueOf)
  .collect(Collectors.joining(", "));

This separates the numbers with a comma, but you can choose whatever you like.

CodePudding user response:

It is possible to use Arrays.deepToString method to convert a 2D array into a string:

String str = Arrays.deepToString(numbers);
  • Related