Doubt when picking map value

4

Hello. When I print the values and keys of Map , it comes from the bottom up. I wanted to know how I can get it 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
    }
}
    
asked by anonymous 10.01.2017 / 14:03

1 answer

4

HashMap gives no guarantee as to the order of the elements. The elements there may end up being removed in any order.

However, if you use LinkedHashMap instead of Map :

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

This will get them sorted by insertion order.

Another way is to get them sorted alphabetically. Use TreeMap in this case:

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

You can customize the order of the elements also by using constructor of TreeMap that receives Comparator .

    
10.01.2017 / 14:08