Junior — Middle
How is element search performed in HashMap by its key?
sobes.tech AI
Answer from AI
In Java, searching for an element in a HashMap by key is done using the get(Object key) method. HashMap uses the hash function of the key for quick access to the value.
Example:
import java.util.HashMap;
public class Example {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 5);
map.put("banana", 3);
Integer value = map.get("apple");
if (value != null) {
System.out.println("Value for key 'apple': " + value);
} else {
System.out.println("Key not found");
}
}
}
When calling map.get("apple"), HashMap computes the hash of the key "apple", finds the corresponding bucket, and returns the associated value.