Java Map
In this post, I will introduce HashMap, LinkedHashMap and Hashtable in Java as well as their corresponding methods.
Introduction to Map
-
An element in a map contains two values, a key and a value.
-
Keys in the map are not allowed to be repeated.
-
HashMap is implemented by hash table; therefore, its access efficiency is super fast.
-
Before JDK 1.8, hash table is implemented by array plus linked list.
-
After JDK 1.8, hash table is implemented by array plus linked list / red black tree (if the length is greater than 8).
-
LinkedHashMap is an ordered collection.
Common Methods
// put(k, v): If k is not duplicated, it returns null. Else it returns the value that is replaced.
private static void show01() {
Map<String, String> map = new HashMap<>();
String v1 = map.put("Jason", "Kevin");
System.out.println(v1); // null
String v2 = map.put("Jason", "Joey");
System.out.println(v2); // Kevin
System.out.println(map); // {Jason=Joey}
}
// remove(k): If k is existed, it returns v. Else it returns null.
private static void show02() {
Map<String, Integer> map = new HashMap<>();
map.put("Jason", 1);
Integer v1 = map.remove("Jason");
System.out.println(v1); // 1
Integer v2 = map.remove("Kevin");
System.out.println(v2); // null
}
// get(k): If k is existed, it returns v. Else it returns null.
private static void show03() {
Map<String, Integer> map = new HashMap<>();
map.put("Jason", 1);
System.out.println(map.get("Jason")); // 1
System.out.println(map.get("Kevin")); // null
}
// containsKey(k): If k is existed, it returns true. Else it returns false.
private static void show04() {
Map<String, Integer> map = new HashMap<>();
map.put("Jason", 1);
System.out.println(map.containsKey("Jason")); // true
System.out.println(map.containsKey("Kevin")); // false
}
Iterate Map Approach 1: (Key -> Value)
// Use keySet() method to collect all keys of the map
private static void demo01() {
Map<String, Integer> map = new HashMap<>();
map.put("Jason", 177);
map.put("Chan", 172);
map.put("Hung", 178);
Set<String> set = map.keySet();
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String key = it.next();
System.out.println(key + ": " + map.get(key));
}
}
Iterate Map Approach 2: (Map.Entry<K, V>)
// entrySet() stores all entries out of map in a set
private static void demo01() {
Map<String, Integer> map = new HashMap<>();
map.put("Jason", 177);
map.put("Chan", 172);
map.put("Hung", 178);
Set<Map.Entry<String, Integer>> set = map.entrySet();
Iterator<Map.Entry<String, Integer>> it = set.iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> entry = it.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + ": " + value);
}
}
Hashtable
-
’null’ cannot be used as key or value in Hashtable.
-
Hashtable and Vector are all replaced by more advanced collections (HashMap, ArrayList) after JDK 1.2.
-
However, ‘Properties’ (A derived class of Hashtable) is still popular.