1
I’m trying to do this exercise, I don’t know where I’m going wrong. Can you help me?
I need to create a map that has the number of characters of a city name and by value in a list of all names with that number of characters.
A print must be made indicating the city names and the number of characters the names have. Try to have as few lines as possible.
Like I did. If you have suggested improvements...
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class testeJava {
    public static void main(String[] args) {
        HashMap<Integer,String> hm=new HashMap<Integer,String>();
        Scanner nomeCidade = new Scanner(System.in);
        Scanner qtdCidade = new Scanner(System.in);
        System.out.println("Quantidade de Cidade a Adicionar?");
        int qtd = qtdCidade.nextInt();
        for (int i = 0; i < qtd; i++) {
            System.out.println("Informe Nome da Cidade?");
            String nome = nomeCidade.nextLine();
            hm.put(i,nome);
            for (int j = 0; j < nome.length(); j++) {
                if(hm.containsKey(nome.charAt(j))){
                //ESTA DANDO ERRO NESSA LINHA ABAIXO SOLICITANDO CAST.
                    hm.put(nome.charAt(j),hm.get(nome.charAt(j))+1); 
                } else {
                    hm.put(nome.charAt(j), 1);
                }
            }
        }
        for(Map.Entry m:hm.entrySet()){  
               System.out.println(m.getKey()+" "+m.getValue());  
        } 
        nomeCidade.close();
        qtdCidade.close();
    }
}
						
Thanks Victor for the tips. When you say, diamond syntax if possible: you mean:
Map<Integer, List<String>> map = new HashMap<>();Omap.computeit’s kind of confusing to me, I’ll study more about it, it seems like it’s a lambda syntax, it ?– Slinkey99
@Slinkey99 Yes, I’m using lambda syntax here. That’s the diamond
<>even.– Victor Stafusa