HashMap object as key and sort – Code

HashMap is key-value data structure. From the key you can find the value by O(1) complexity. it is the most used data structure in Java collection.

HashMap is easy to use by following three steps, create the HashMap object, call put() and get(). But if you need to use object as key, you need extra work – override hashCode() and equals(). Also you might have to implement comparable if you need to sort them. HashMap object as key and sort introduces this technique.

Define a class of your choice, and use it as the key in the HashMap. Also sort the HashMap by the key.

Java Code: define class Fruit

Orange 30.7 Florida -victory
Apple 40.09 Japan -Queen Mary
Orange 25.7 California -Black Pearl
Banana 20.13 Hawaii -Mayflower
Mango 15.7 Philippines -Jenny

O Notation:
Time complexity: O(1)
Space complexity: O(1)

Java Code: sort by key using HashTree

Mango 15.7 Philippines – Jenny
Banana 20.13 Hawaii – Mayflower
Orange 25.7 California – Black Pearl
Orange 30.7 Florida – victory
Apple 40.09 Japan – Queen Mary

O Notation:
Time complexity: O(logn), n is the number of elements in hash.
Space complexity: O(n)

If you have any questions or want to put comments, please post at youtube. I will answer you!

Download HashMapObjectAsKey.zip
HashMap object as key and sort (YouTube)
Data structures and Java collections

Comments are closed