Sobes.tech
Middle+

What is the search speed in HashMap (average and worst case)?

sobes.tech AI

Answer from AI

HashMap in Java provides an average access time to an element of about O(1) due to the use of a hash function for quick key lookup.

However, in the worst case, when there are many collisions and all elements end up in a single bucket, the access speed can degrade to O(n), where n is the number of elements in the map.

Starting from Java 8, when there are many collisions within a single bucket, the data structure changes from a linked list to a balanced tree (TreeMap), which improves the worst-case access time to O(log n).

Example:

HashMap<String, Integer> map = new HashMap<>();
map.put("key1", 100);
Integer value = map.get("key1"); // Average time O(1)