Java hashmap
Created By: chatGPT
In Java, a HashMap is a part of the Java Collections Framework and is used to store data in a key-value pair format. It allows for null values and one null key. A HashMap is a hash table implementation of the Map interface, and it is important because it provides constant-time performance for basic operations (e.g., add, remove and contains) assuming the hash function disperses the elements properly among the buckets.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Creating a HashMap
HashMap<String, Integer> map = new HashMap<>();
// Adding key-value pairs
map.put("Apple", 40);
map.put("Banana", 30);
map.put("Orange", 20);
// Accessing a value
Integer value = map.get("Banana");
System.out.println("Value for key 'Banana': " + value);
// Checking if a key exists
if (map.containsKey("Apple")) {
System.out.println("Apple is available in the map.");
}
// Removing a key-value pair
map.remove("Orange");
System.out.println("Map after removing 'Orange': " + map);
// Iterating over the keys
for (String key : map.keySet()) {
System.out.println(key + " - " + map.get(key));
}
}
}
When using a HashMap, it's important to understand that it does not guarantee the order of the map. If you need to maintain the order of insertion, you should use LinkedHashMap. Additionally, if you require a sorted order, consider using a TreeMap instead.
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// Creating a LinkedHashMap
LinkedHashMap<String, Integer> linkedMap = new LinkedHashMap<>();
// Adding key-value pairs
linkedMap.put("Dog", 1);
linkedMap.put("Cat", 2);
linkedMap.put("Bird", 3);
// Iterating in insertion order
for (Map.Entry<String, Integer> entry : linkedMap.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
}
To ensure the stability of key-value pairs in a multi-threaded environment, consider using ConcurrentHashMap. This offers better performance in concurrent situations by employing segment locks.
import java.util.concurrent.ConcurrentHashMap;
public class Main {
public static void main(String[] args) {
// Creating a ConcurrentHashMap
ConcurrentHashMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();
// Adding key-value pairs
concurrentMap.put("First", 1);
concurrentMap.put("Second", 2);
// Accessing a value
System.out.println("Value for key 'First': " + concurrentMap.get("First"));
}
}