Doubt when taking Map’s value

Asked

Viewed 315 times

4

Hello. When I print out the values and key of the Map, it comes from bottom to top. I wonder how I do to pick up from top to bottom.

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class ClassDebug {
    public static void main(String a[]){
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("Alemanha", 7);
        map.put("Brasil ", 1);
        for(Entry<String, Integer> entry: map.entrySet()) {
            System.out.println(entry.getKey());
        }
           // Imprime: Brasil
           // Imprime: Alemanha

         // Eu quero que imprima:

        // Alemanha e Brasil :V
    }
}
  • And while you read that question, another goal from Germany.

1 answer

4


The HashMap does not offer any guarantee as to the order of the elements. The elements there may end up being removed in any order.

However, if you use one LinkedHashMap instead of a Map:

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

This will cause them to be ordered in the insertion order.

Another way is to sort them alphabetically. Use the TreeMap in this case:

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

You can customize the order of the elements also using the builder of TreeMap who receives a Comparator.

  • Thanks man, it worked right here.

Browser other questions tagged

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