Mithun Khatri
Mithun Khatri

Reputation: 696

Insertion in HashMap not working properly

I am inserting a sorted object into a HashMap but its not getting sorted.

Map<Long, Object> sortedObject = new HashMap(Long, Object>();    
for(Object sortedObject : sortedObjectList)
    {
      sortedMap.put(sortedObject.getId(), sortedObject);
    }

    syso(new Gson().toJson(sortedMap);

In output I was expecting sorted map, but its random. Please help.

Upvotes: 0

Views: 98

Answers (2)

Kiran
Kiran

Reputation: 20293

Hashmap is unordered. Use Treemap to sort. Try this:

Map<Long, Object> sortedObject = new HashMap<Long, Object>(); 

for(Object sortedObject : sortedObjectList)
{
    sortedMap.put(sortedObject.getId(), sortedObject);
} 
System.out.println("Unsort Map......");
System.out.println(new Gson().toJson(sortedMap);

System.out.println("Sorted Map......");
Map<String, String> treeMap = new TreeMap<String, String>(sortedMap);
System.out.println(new Gson().toJson(treeMap);

TreeMap is an example of a SortedMap, which means that the order of the keys can be sorted, and when iterating over the keys, you can expect that they will be in order.

HashMap on the other hand, makes no such guarantee. Therefore, when iterating over the keys of a HashMap, you can't be sure what order they will be in.

HashMap will be more efficient in general, so use it whenever you don't care about the order of the keys.

HashMap is specified to be O(1): 'constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets'. TreeMap is specified to 'guaranteed log(n) time cost for the containsKey, get, put and remove operations. Go through Javadocs that I shared for more details.

Upvotes: 1

Ankur Kumawat
Ankur Kumawat

Reputation: 466

HashMap is not sorted, It stores in Key-Value pairs. Values are mapped with the corresponding keys.

Upvotes: 0

Related Questions