Reputation: 2803
I have a treemap:
private Map<String, Integer> dataMap = new TreeMap<String, Integer>();
and later in the code I have the following part:
for (String item : data) {
JSONObject itemJson = new JSONObject(item);
System.out.println("-- before " + itemJson.getString("dataLabel") + " " + itemJson.getInt("dataValue"));
dataMap.put(itemJson.getString("dataLabel"), itemJson.getInt("dataValue"));
}
for(String data : dataMap.keySet()) {
System.out.println("-- after " + data);
}
The first loop displays sorted elements, such as:
-- before January 1
-- before February 2
-- before March 3
-- before April 4
.
.
.
but the second loop mixes the order:
-- after April
-- after February
-- after January
-- after March
.
.
.
Why so? and how can I get sorted results on the second loop? And by sorted I mean the same order as I was adding them during the first loop? Thanks
Upvotes: 0
Views: 1005
Reputation: 16813
The keySet()
method is used to get a Set view of the keys contained in this map.
for (String data : dataMap.keySet())
That gives you the keys.
Now in that loop, get each value from the dataMap
using the key (data
), and print it.
check following example
for (Map.Entry<K, V> data: dataMap.entrySet()) {
System.out.println("Key: " + data.getKey() + ". Value: " + data.getValue());
}
or
HashMap
does not define any particular ordering of its element. Therefore the "reverse" order isn't defined either.
For a TreeMap
, you can use descendingMap()
.
Upvotes: 0
Reputation: 85809
TreeMap
sorts the entries by key, not by value. From the docs (emphasis mine):
A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys (this is your case), or by a Comparator provided at map creation time, depending on which constructor is used.
The output is correct because the strings are sorted alphabetically.
how can I get sorted results on the second loop? And by sorted I mean the same order as I was adding them during the first loop?
Use a LinkedHashMap
instead, because stores the entries according to the order they were inserted. From the docs (emphasis mine):
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.
Upvotes: 6