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

136
Visualizações
How to write method array to Map

I need to write a method that will convert the mass into Map

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

0

i is an array, so when you put it as the key of your Map, you get a Map<Object[],Object>.

You don't need a nested loop:

public Map<Character, Integer> arrayToMap(Object[][] args) {
    Map<Character, Integer> map = new LinkedHashMap<>();
    for (Object[] i : args) {
        map.put((Character) i[0], (Integer) i[1]);
    }
    return map;
}

Each inner array of your 2D array should become a pair of key and value in the output Map.

over 4 years ago · Santiago Trujillo Relatório

0

Use Stream API with Callectors.toMap method:

public static Map<Character, Integer> arrayToMap(Object[][] arr) {  
  return Arrays.stream(arr)
               .collect(Collectors.toMap(o -> (Character)o[0],
                                         o -> (Integer)o[1],
                                         (oldV, newV) -> newV,
                                         LinkedHashMap::new
                                         ));
}
over 4 years ago · Santiago Trujillo Relatório

0

2D array in Java is an array of arrays; i.e. in your example, you have a 1D array of 1D arrays with exactly 2 elements [char, int]

public static void main(String[] args) {
    Object[][] arr = {
            { '1', 1 }, { ' ', 5 }, { '2', 2 }, { '3', 3 },
            { '4', 4 }, { '5', 5 }, { '6', 6 } };

    Map<Character, Integer> map = arrayToMap(arr);
    System.out.println(map);
}

public static Map<Character, Integer> arrayToMap(Object[][] arr) {
    Map<Character, Integer> map = new HashMap<>();

    for (int i = 0; i < arr.length; i++)
        map.put((char)arr[i][0], (int)arr[i][1]);

    return map;
}
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