Home > front end >  Java: Convert a 2d Array of String in a 1d Array of char
Java: Convert a 2d Array of String in a 1d Array of char

Time:10-09

how can I convert a 2d Array of String: String[][] = {{"A", "-.-"},{"B", "..-"}} into a array of char: char[] c = {"A","B"}?

Can somebody help me?

CodePudding user response:

You have an input and you create an output of the same .length as the input's .length, then loop an i index through the range of 0 ...length - 1 and get the i'th record's 0'th record (the letter) and get its first char via charAt(0).

String[][] input = new String[][] {{"A", "-.-"},{"B", "..-"}};
char[] output = new char[input.length];
for (int i = 0; i < input.length; i  ) {
    output[i] = input[i][0].charAt(0);
}

CodePudding user response:

Using streams.

final char[] result = Arrays.stream(input)
                .map(i -> String.valueOf(i[0].charAt(0)))
                .collect(Collectors.joining())
                .toCharArray();
  • Related