In Java, a HashMap is a class that implements the Map interface and stores key-value pairs in a hash table. It provides fast lookups and insertion, making it a useful data structure for storing and accessing data efficiently.
Here's an example of how you can create and use a HashMap in Java:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// create a hash map
Map<String, Integer> map = new HashMap<>();
// add key-value pairs to the map
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Orange", 3);
// get the value for a key
int value = map.get("Apple");
System.out.println(value); // prints 1
// check if a key is in the map
boolean containsKey = map.containsKey("Apple");
System.out.println(containsKey); // prints true
// remove a key-value pair from the map
map.remove("Apple");
containsKey = map.containsKey("Apple");
System.out.println(containsKey); // prints false
// iterate over the map
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
This code creates a HashMap called map and adds three key-value pairs to it: "Apple" => 1, "Banana" => 2, and "Orange" => 3. It then gets the value for the key "Apple" and prints it to the console. It also checks if the key "Apple" is in the map and removes it. Finally, it iterates over the map and prints the key-value pairs.
For more information about HashMap and other collections in Java, you can refer to the Java documentation (https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html).