Hashmap Flashcards
How does hashmap work
It stores key value pair and works based on the principle of hashing
Use hashing algorithm to generate hash code and compare with the hashcode() and equals() method
What does hashmap store in the bucket (value)
It store both key and value
What happens if two different. Hashmap key objects have same hashcode
Stored on same bucket in a linked list and the key equals method will help identify which entry in the list
Hashmap, treemap and linkedhashmap
Hashmap - O (1) insertion and lookup. No order for keys
Treemap - O(log n) insertion and lookup . Keys are ordered in sorted manner.
Linkedhashmap - O(1) insertion and lookup. Keys are ordered by insertion order
Iterate through a map
for (Map.Entry entry : map.entrySet())
System.out.println(“Key = “ + entry.getKey() +
“, Value = “ + entry.getValue());
Sort by descending order
Collections.sort(result, (r1,r2) -> map.get(r1).equals(map.get(r2)) ?
r1.compareTo(r2) : map.get(r2).compareTo(map.get(r1)));