javajava-collections-api

How do I get the TreeMap (or other Map if necessary) entries in sorted order?


I need a set that allows me to order element by key. The keys are Integer, but they are not sequential. This is and example of what I have:

<3, Alessandro>
<12, Mario>
<1, Marco>

And I need to print those elements in this order:

Marco    
Alessandro
Mario

I tried using TreeMap, but I can't make a loop like this:

for(int i = 0; i < treeMap.size(); i++){    
    System.out.println(treeMap.get(i));         
}

because the key is not sequential and I would get an error when calling treeMap.get(), because I don't know the Key integer.


Solution

  • get gets by key, not index position. Iterate over the entrySet or keySet.

    Setup:

    TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
    
    treeMap.put(3, "Alessandro");
    treeMap.put(12, "Mario");
    treeMap.put(1, "Marco");
    

    Example using entrySet, in which case you get a Map.Entry<Integer, String> for each iteration:

    for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
        System.out.println(entry.getValue());
    }
    

    Or if you prefer keySet, which gives you the keys (Integers):

    for (Integer key : treeMap.keySet()) {
        System.out.println(treeMap.get(key));
    }
    

    Either way, the above results in:

    Marco
    Alessandro
    Mario
    

    E.g., ordered by the natural order of the keys.