Operations with Hashmap

Asked

Viewed 592 times

0

Good afternoon guys, I need to do some operations using Hashmap. I am new in the area.

I have the following map

protected Map<String, Map<String, Integer>> elementos = new HashMap<>();`

The first String is a key, the value is a map that contains a key like String and an Integer value.

I need to go through all the values that are in this hashmap, that is, all the internal hashMaps. So I need to make comparisons and sort. Example:

HashMap<"texto1",HashMap<"Cachorro", 3>

HashMap<"texto2",HashMap<"Peixe", 2>

Ai would make a comparison of the type, "If "dog" == "Fish" -> Listfrequencia = (3-2); Finally, somehow, after this calculation sort by saying which text comparison is less. First post here. Java `

  • I didn’t understand the part of the comparison, in the part that says Se "cachorro" == "Peixe" -> Listafrequencia = (3-2); could explain otherwise?

  • So, this Hashmap has a String as key and an Integer type value. The comparison I speak would be: If String equals the hashmap String, do this operation that is contained in the Integer Hashmap Type value field ( 3 for dog and 2 for fish in case.) Obs, this number is the amount of times this string is in a given string.

1 answer

1


If this is a learning exercise (college or course) the full statement would help, the way you explained the problem is confusing. Follow some guidance:

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

    //percorre  a map
    for (String key : elementos.keySet()) {

        int total = 0;

        //percorre a map interna, agrupado por chave 
        for (Integer i : elementos.get(key).values()) {
            total=i+total;
        }

        System.out.println(key + total);

    }
  • That, I am sorry if I have not been very clear, is that the exercise is extremely large and I was left with doubts on this part. But already solved, I even used something very similar to what you put here. Thank you.

Browser other questions tagged

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