HomeSearch

Java HashMap Examples

Use the HashMap class from java.util.HashMap. Perform fast key lookups with hashing.
HashMap. Consider a labyrinth of paths. How can we know which ones we have already traveled down? A HashMap could allow us to record these paths and not follow them again.
With its fast search algorithm, we would not waste time iterating over keys. We use java.util.HashMap and call the put() and get methods.
First example. We create an example HashMap with keys of type String, values of Integer. On the right side of the declaration, the diamond inference feature is used.

Syntax: When we use a diamond, the left-side arguments are automatically chosen. This reduces syntax noise.

Put: The put method receives 2 arguments: the key we are trying to add, and the value linked to that key.

Get: We call the get() method. This looks into the HashSet and, if found, returns the value for the key.

Caution: Please be careful not to call the get() method on a key that does not exist. An exception will be thrown.

Java program that uses HashMap import java.util.HashMap; public class Program { public static void main(String[] args) { // Create new HashMap. // ... Uses diamond inference on right side. HashMap<String, Integer> hash = new HashMap<>(); // Put three keys with values. hash.put("dog", 1); hash.put("cat", 2); hash.put("rabbit", 3); // Look up some known values. int a = hash.get("dog"); int b = hash.get("cat"); // Display results. System.out.println(a); System.out.println(b); } } Output 1 2
Keys. A HashMap often contains many keys. We can loop through these keys by first calling the keySet() method. We loop over the Set returned by keySet.

Tip: It is also possible to loop over the entries in the HashMap. This can eliminate the need for a value lookup in the for-loop.

For
Java program that loops over keys import java.util.HashMap; import java.util.Set; public class Program { public static void main(String[] args) { // Create HashMap of three entries. HashMap<String, Integer> h = new HashMap<>(); h.put("apple", 1); h.put("peach", 2); h.put("guava", 3); // Get keys. Set<String> keys = h.keySet(); // Loop over String keys. for (String key : keys) { System.out.println(key); } } } Output guava apple peach
Loop over entrySet. Each key has a value in the HashMap. We can loop over these together (without doing additional lookups) by calling entrySet() in a for-statement.

Entry: We must specify an Entry with the key and value types of the HashMap. We then can call getKey and getValue.

Ordering: The HashMap does not remember the order we add items to it. To maintain ordering, please consider a LinkedHashMap.

LinkedHashMap
Java program that loops over HashMap, entrySet import java.util.HashMap; import java.util.Map.Entry; public class Program { public static void main(String[] args) { // Create HashMap and put 3 entries in it. HashMap<String, Integer> values = new HashMap<>(); values.put("Java", 6); values.put("Python", 4); values.put("C#", 5); // Loop over HashMap with entrySet. // ... The ordering is not maintained. for (Entry<String, Integer> pair : values.entrySet()) { System.out.println(pair.getKey() + "::" + pair.getValue()); } } } Output C#::5 Java::6 Python::4
ContainsKey. Sometimes we need no value from the HashMap. Instead we just want to see if the key exists. We use the containsKey method for this purpose.

True: It returns true if the key is found, and false otherwise. We often test it in an if-statement.

If

Tip: The containsKey method is fast because a hash code is used to locate the key. Using containsValue() is slower—no hash is available.

Java program that uses containsKey import java.util.HashMap; public class Program { public static void main(String[] args) { // Create an Integer HashMap. HashMap<Integer, Integer> h = new HashMap<>(); h.put(1, 1000); h.put(20, 1001); h.put(300, 1003); // Use containsKey. if (h.containsKey(1)) { System.out.println("1 was found"); } if (h.containsKey(300)) { System.out.println("300 was found"); } if (!h.containsKey(400)) { System.out.println("400 was not found"); } } } Output 1 was found 300 was found 400 was not found
ContainsValue returns true if a specified value exists. Keys are not checked, just values. To get keys with a value, we must use a loop—more than one key may have a single value.
Java program that uses containsValue import java.util.HashMap; public class Program { public static void main(String[] args) { // Create a HashMap of fruit and their color. HashMap<String, String> fruit = new HashMap<>(); fruit.put("apple", "red"); fruit.put("orange", "orange"); fruit.put("banana", "yellow"); fruit.put("raspberry", "red"); // See if there is a red value. if (fruit.containsValue("red")) { System.out.println("Red fruit detected!"); // Loop over all keys and print them if they have "red" values. for (String key : fruit.keySet()) { if (fruit.get(key) == "red") { System.out.println(key); } } } } } Output Red fruit detected! raspberry apple
Size. Every HashMap has a size. This is the count of entries (or of keys). For each key-value pair we add to HashMap, its size increases by one. The size() method returns this count.
Java program that uses size import java.util.HashMap; public class Program { public static void main(String[] args) { // ... Create empty HashMap. HashMap<Integer, Integer> map = new HashMap<>(); System.out.println(map.size()); // ... Add one entry. map.put(1, 100); System.out.println(map.size()); // Add two more entries. map.put(2, 200); map.put(3, 300); System.out.println(map.size()); } } Output 0 1 3
IsEmpty. This returns true if the HashMap has a size of zero. It is the same thing as testing size() >0 but it may be easier to read. Testing for empty collections is a common requirement.

Boolean: This method returns a Boolean. It is often used within if-statements. But the Boolean can be used in any way.

Java program that uses isEmpty import java.util.HashMap; public class Program { public static void main(String[] args) { HashMap<String, Boolean> map = new HashMap<>(); // The HashMap is currently empty. if (map.isEmpty()) { System.out.println("It is empty"); } map.put("cat", true); map.put("dog", false); // IsEmpty now returns false. System.out.println(map.isEmpty()); } } Output It is empty false
Values. We can get a collection of a HashMap's values with the values method. We must specify the type for values in the HashMap. Here we get String values.

Note: We then loop over the HashMap. We use a foreach-loop. Each element is of String type.

Java program that uses values import java.util.Collection; import java.util.HashMap; public class Program { public static void main(String[] args) { HashMap<String, String> hash = new HashMap<>(); hash.put("cat", "black"); hash.put("dog", "brown"); hash.put("bird", "blue"); // Get all values from the HashMap. Collection<String> values = hash.values(); for (String value : values) { System.out.println(value); } } } Output blue black brown
GetOrDefault. With this method, we safely get a value from our HashMap. If the key does not exist, no error occurs. Instead, the default value (argument 2) is returned.
Java program that uses getOrDefault import java.util.HashMap; public class Program { public static void main(String[] args) { // Create HashMap and put one key. HashMap<Integer, Integer> hash = new HashMap<>(); hash.put(0, 10); // Get keys 0 and 1, returning -1 if nothing there. int result = hash.getOrDefault(0, -1); // Exists int result2 = hash.getOrDefault(1, -1); // Does not exist System.out.println(result); System.out.println(result2); } } Output 10 -1
PutIfAbsent. Put() will replace an existing value. But putIfAbsent() will not. It only adds the value to the HashMap if no key currently exists for it.

Tip: We can use putIfAbsent repeatedly if only the first encountered key needs to be retained.

Java program that uses putIfAbsent import java.util.HashMap; public class Program { public static void main(String[] args) { // Create HashMap and use putIfAbsent. HashMap<String, Double> hash = new HashMap<>(); hash.putIfAbsent("cat", 1.5); hash.putIfAbsent("cat", 2.0); // ... This returns the first value added. double value = hash.get("cat"); System.out.println(value); } } Output 1.5
Sort keys. A HashMap is unordered. It cannot be directly sorted, but we can sort its keys and process them (and their values) in order. We use keySet and add the keys to an ArrayList.

Collections.sort: We sort the ArrayList containing the keys with this method. The keys are now in ascending order.

Sort
Java program that sorts HashMap import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Set; public class Program { public static void main(String[] args) { HashMap<String, String> hash = new HashMap<>(); hash.put("red", "color"); hash.put("tomato", "fruit"); hash.put("pizza", "lunch"); // Put keys into an ArrayList and sort it. Set<String> set = hash.keySet(); ArrayList<String> list = new ArrayList<String>(); list.addAll(set); Collections.sort(list); // Display sorted keys and their values. for (String key : list) { System.out.println(key + ": " + hash.get(key)); } } } Output pizza: lunch red: color tomato: fruit
Sort EntrySet, values. Sorting the values in a HashMap is somewhat complex. We access the EntrySet, which contains the key-value pairs in the HashMap.

Comparator: We implement a Comparator class called EntryComparator. In compare() it calls compareTo on the Entry's values.

ArrayList: In main, we copy the EntrySet to an ArrayList which can be sorted. We call addAll to add the Entries.

Sort: In ArrayList sort(), we pass our EntryComparer. This sorts the ArrayList of Entries by each Entry's value.

Java program that sorts EntrySets import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Map.Entry; class EntryComparator implements Comparator<Entry<String, Integer>> { public int compare(Entry<String, Integer> arg0, Entry<String, Integer> arg1) { // Compare the values. return arg0.getValue().compareTo(arg1.getValue()); } } public class Program { public static void main(String[] args) { // Create HashMap and add four pairs to it. HashMap<String, Integer> hash = new HashMap<>(); hash.put("bird ", 500); hash.put("zebra", 2); hash.put("cat ", 10); hash.put("dog ", 5); // Copy keySet into ArrayList. // ... Sort with EntryComparator. ArrayList<Entry<String, Integer>> copy = new ArrayList<>(); copy.addAll(hash.entrySet()); copy.sort(new EntryComparator()); // Display. for (Entry<String, Integer> e : copy) { System.out.println(e.getKey() + "..." + e.getValue()); } } } Output zebra...2 dog ...5 cat ...10 bird ...500
Static field. Sometimes many methods want to share the same HashMap. We can place a HashMap in a class as a static field. Then we can access it with static methods on that class.
Java program that uses static HashMap import java.util.HashMap; public class Program { static HashMap<String, String> map = new HashMap<>(); public static void main(String[] args) { // Use static HashMap in static methods. addAnimals(); testAnimals(); } static void addAnimals() { map.putIfAbsent("cat", "black"); map.putIfAbsent("bird", "blue"); } static void testAnimals() { System.out.println(map.getOrDefault("cat", "missing")); System.out.println(map.getOrDefault("?", "missing")); } } Output black missing
HashMap versus ArrayList. In this benchmark we test search speed for the HashMap and for the ArrayList. We create 3-element collections, and then try to find elements.

Version 1: In this version of the code, we search a HashMap for one key. We call containsKey() on the HashMap.

Version 2: Here we search an ArrayList. We call the contains() method on the ArrayList instance.

Result: The HashMap delivers a stunning performance boost. It returns the correct result over 2 times faster than the ArrayList.

Tip: Even for small collection lookups, where only three elements exist, a HashMap locates an element faster. HashMap is a clear win.

Java program that times HashMap, ArrayList import java.util.HashMap; import java.util.ArrayList; public class Program { public static void main(String[] args) throws Exception { HashMap<Integer, Boolean> hash = new HashMap<>(); hash.put(100, true); hash.put(1000, true); hash.put(50, true); ArrayList<Integer> array = new ArrayList<>(); array.add(100); array.add(1000); array.add(50); long t1 = System.currentTimeMillis(); // Version 1: do HashMap lookups. for (int i = 0; i < 10000000; i++) { if (!hash.containsKey(50)) { throw new Exception(); } } long t2 = System.currentTimeMillis(); // Version 2: do ArrayList lookups. for (int i = 0; i < 10000000; i++) { if (!array.contains(50)) { throw new Exception(); } } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } } Output 91 ms, HashMap: containsKey 244 ms, ArrayList: contains
Convert HashMap, ArrayList. To sort a HashMap we can place its keys in an ArrayList, which we sort. With other collections, we can change how we view, and use data stored in a HashMap.Convert HashMap, ArrayList
Hashtable. This collection does the same things as HashMap but is more thread-safe. Hashtable, for this reason, is slower and should usually be avoided.Hashtable
LinkedHashMap. When items are added to a HashMap, the order is not maintained. But with LinkedHashMap, the order is remembered, so we can loop over items in the order they were added.
TreeMap. This is a red-black binary tree. It provides fast access, insertion and removal. TreeMap implements many of the same methods found on HashMap.TreeMap
EnumMap. We can place enums as keys within the HashMap. But Java provides an optimized EnumMap that looks up enum keys faster. It uses similar syntax.EnumMap
HashSet. This is a HashMap with no values. In a HashSet we can invoke methods that are based on set theory. Sometimes we can replace a HashMap with a HashSet.HashSet
A summary. HashMap is an important optimization. Most programs that loop over large arrays can be improved with a HashMap. But testing is still often needed.
Fast lookups are critical. If a collection with poor lookup performance is used, a program may (with large data sets) become unusable. With its hashing algorithm, HashMap is faster here.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls