`java.util` is a package library in Java that contains various utility classes such as `HashMap`. `HashMap` is a collection class that is used to store key-value pairs, where each key is unique.
Example 1: Creating a HashMap and adding elements to it.
``` java import java.util.HashMap;
public class HashMapExample { public static void main(String[] args) { HashMap map = new HashMap<>(); map.put("John", 20); map.put("Mary", 25); map.put("Peter", 30);
Example 2: Retrieving an element from HashMap using a key.
java import java.util.HashMap;
public class HashMapExample { public static void main(String[] args) { HashMap map = new HashMap<>(); map.put("John", 20); map.put("Mary", 25); map.put("Peter", 30);
Integer age = map.get("Mary"); System.out.println(age); // 25 } }
Example 3: Removing an element from HashMap using a key.
java
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap map = new HashMap<>();
map.put("John", 20);
map.put("Mary", 25);
map.put("Peter", 30);
map.remove("Mary");
System.out.println(map); // {Peter=30, John=20}
}
}
```
Java HashMap - 30 examples found. These are the top rated real world Java examples of java.util.HashMap extracted from open source projects. You can rate examples to help us improve the quality of examples.