Exercise with Hashmap

Asked

Viewed 688 times

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();
    }
}

1 answer

3

First, you should only wear one Scanner. Never use or create more than one and only one new Scanner(System.in). And there’s no point in shutting it down.

Second, which class names must have uppercase letters. That is, use TesteJava instead of testeJava.

Third, that as you said yourself, the values of the Map should be a list of city names.

Fourth, who mix the nextInt() with the nextLine() in the Scanner brings unexpected and confusing results. See in this my other answer an explanation of this.

Fifth, use the diamond syntax if possible.

Sixth, prefer to declare variables whose types are abstractions, not implementations. That is, avoid variables whose type is HashMap instead of Map.

Seventh, what you want to do is much easier if you use the method compute(K, BiFunction<? super K, ? super V, ? extends V>).

Eighth, avoid as much as possible using generic types without generics.

Here’s your corrected code:

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

class TesteJava {

    public static void main(String[] args) {

        Map<Integer, List<String>> map = new HashMap<>();

        Scanner scan = new Scanner(System.in);

        System.out.println("Quantidade de cidades a adicionar?");
        int qtd = Integer.parseInt(scan.nextLine());

        for (int i = 0; i < qtd; i++) {
            System.out.println("Nome da " + (i + 1) + "a cidade?");
            String nome = scan.nextLine();
            map.compute(nome.length(), (k, v) -> {
                List<String> nomes = v != null ? v : new ArrayList<>();
                nomes.add(nome);
                return nomes;
            });
        }

        for (Map.Entry<Integer, List<String>> entry : map.entrySet()) {  
            System.out.println(entry.getKey() + " " + entry.getValue());  
        } 
    }
}

If that code is entered:

21
Bauru
Poá
Londrina
Franca
Itapevi
Osasco
Salvador
Suzano
São Paulo
Vitória
Cuiabá
Maceió
Belém
Curitiba
Macapá
Rio Branco
Manaus
Belo Horizonte
Recife
Itu
Rio de Janeiro

This will be the output produced at the end:

3 [Poá, Itu]
5 [Bauru, Belém]
6 [Franca, Osasco, Suzano, Cuiabá, Maceió, Macapá, Manaus, Recife]
7 [Itapevi, Vitória]
8 [Londrina, Salvador, Curitiba]
9 [São Paulo]
10 [Rio Branco]
14 [Belo Horizonte, Rio de Janeiro]

See here working on ideone.

  • Thanks Victor for the tips. When you say, diamond syntax if possible: you mean: Map<Integer, List<String>> map = new HashMap<>(); O map.compute it’s kind of confusing to me, I’ll study more about it, it seems like it’s a lambda syntax, it ?

  • 1

    @Slinkey99 Yes, I’m using lambda syntax here. That’s the diamond <> even.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.