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
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.