HashMap object as key and sort – Code

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.

Question:
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

Output:
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

Output:
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)

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

Recommended:
Download HashMapObjectAsKey.zip
HashMap object as key and sort tutorial
The complete list of coding interview questions

Comments are closed