Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
How to convert two dimensional array of string into one of type int?

How can I convert a double array of type String to a double array of type int ?

    @PostMapping("/hole/coordinate")
    @ResponseBody
    public String saveCoordinate(@RequestBody Map<String, Object> params) {
        System.out.println("params = " + params);
        System.out.println("params = " + params.get("coordinate"));
        
        return "success";
    }

System.out.println(params.get("coordinate")); store [[445, 292], [585, 331], [612, 223], [205, 532]] There are m 2 elements of the double array. ex) [a,b],[c,d].....m At this time, I want to receive the result in the data type of int[][], not String.

I was wondering how can I convert from String to int[][].

I tried like below

int[] arr= Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();
for (int i : arr) {
    System.out.println("i = " + i);
}

but it give me

4
4
5
2
9
2
...

Best Regards!

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can try the below code if you are trying to convert String to int[]

import java.util.stream.*;
public class MyClass {
    public static void main(String args[]) {
      String str = "[[445, 292], [585, 331], [612, 223], [205, 532]]";
      int[] arr= Stream.of(str.replaceAll("[\\[\\]\\ ]", "").split(",")).mapToInt(Integer::parseInt).toArray();
        for (int i : arr) {
            System.out.println("i = " + i);
        }
    }
}

It prints below values as output:

i = 445
i = 292
i = 585
i = 331
i = 612
i = 223
i = 205
i = 532
over 4 years ago · Santiago Trujillo Relatório

0

    Try this. It creates a matrix of coordinates.

    String str = "[[445, 292], [585, 331], [612, 223], [205, 532]]";
    List<String> numbers = List.of(str.split(",| |\\[|\\]"));
    List<String> onlyNumbers = numbers.stream()
                                      .filter(number -> !number.equals("") && !number.equals(" "))
                                      .toList();
    Integer[][] coordinates = new Integer[onlyNumbers.size()][2];
    int counter = 0;
    for(int i=0; i < onlyNumbers.size() - 1; i+=2){
        coordinates[counter][0] = Integer.valueOf(onlyNumbers.get(i));
        coordinates[counter][1] = Integer.valueOf(onlyNumbers.get(i+1));
        counter++;
    }
over 4 years ago · Santiago Trujillo Relatório

0

You could parse it manually, as done in other answers, but since you are using spring, you should use the tools it offers you.

Spring uses jackson's ObjectMapper for serialization and deserialization by default. A bean of this type is preconfigured for you, you can autowire it in your controller method and use it. Then the entire parsing is this:

int[][] parsedCoordinates = objectMapper.readValue(coordinates, int[][].class);

And your controller method looks like this:

@PostMapping("/hole/coordinate")
@ResponseBody
public String saveCoordinate(@RequestBody Map<String, Object> params, ObjectMapper objectMapper) {
    System.out.println("params = " + params);
    System.out.println("params = " + params.get("coordinate"));
    //get string from your params
    String coordinates = "[[445, 292], [585, 331], [612, 223], [205, 532]]";
    int[][] parsedCoordinates;
    try {
        parsedCoordinates = objectMapper.readValue(coordinates, int[][].class);
    } catch (JsonProcessingException exc) {
        //that's a bad way to handle error, but it's an example
        //you might return error message like - invalid coordinate format
        //or whatever you need
        exc.printStackTrace();
        throw new RuntimeException(exc);
    }
    //printing parsed result to check it
    for (int i = 0; i < parsedCoordinates.length; i++) {
        int[] inner = parsedCoordinates[i];
        for (int j = 0; j < inner.length; j++) {
            System.out.printf("pos %d-%d, value %d%n", i, j, parsedCoordinates[i][j]);
        }
    }
    return "success";
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda