Java Map: 8 examples with HashMap and LinkedHashMap classes
The Map interface in Java
The Map is an interface in Java like the List and Set are interfaces of Collection. The Map interface has taken the place of Dictionary abstract class.
The Map object stores the data in the key – value pairs where only one value can be mapped to a key.
The keys cannot be duplicated in a map.
The keys of a Java Map can be of numeric or string etc type. Being able to use keys as strings let us establish a strong relationship between key and values for longer term unlike arrays, sets or lists which index is based on numeric values.
For example, you may create a telephone directory collection based on names as keys and phone numbers as values (I will show you in examples).
As the Map is an interface, this is implemented by a few classes. These classes include HashMap, TreeMap, and LinkedHashMap.
I will show you examples of declaring, adding key-value pairs, and accessing the values by keys in Maps by using implementation classes in the following part, so keep reading. I will also show you examples of a few useful methods of Map Java interface.
A demo of creating a Java Map with HashMap
In this example, a map object is created with the HashMap class. The Java HashMap class does not guarantee the order of the map. For example, the order of entries in a map may vary as compared to it is displayed. This is evident in the example below. The HashMap provides all map operations while it also permits null key and values.
In the example, the type of keys is set as String and values as integers. For demonstration, the phone directory map contains the names as keys and numbers as values. Have a look:
See online demo and code
The code of creating and displaying a Map:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.*; public class map_demo { public static void main(String[] args) { Map<String, Integer> tel_dir_map = new HashMap<String, Integer>(); tel_dir_map.put("Mike", 4567891); tel_dir_map.put("Nina", 1424541); tel_dir_map.put("Danial", 45678977); tel_dir_map.put("Usman", 14712314); System.out.println("Telephone Numbers:"); System.out.print("\t" + tel_dir_map); } } |
You see, the keys and values are separated by a comma as using the put method. In the output, you can see the order of insertion is different to the order displayed by using the System.out.print.
A demo of creating a Map with LinkedHashMap
If you require the same order of iteration as map entries are in the Map object, then use the Java LinkedHashMap implementation class. The LinkedHashMap guarantees the same iteration order unlike the HashMap class even if a key is re-entered.
See this example where a Map is created with LinkedHashMap class. The employee salary map contains four entries with employee Name and the respective salary.
For iterating through the LinkedHashMap, a for loop is used and key / value pairs are displayed as follows:
See online demo and code
The code of creating the map with LinkedHashMap:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import java.util.*; public class map_demo { public static void main(String[] args) { Map<String, String> salary_map = new LinkedHashMap<String, String>(); salary_map.put("Mike", "$5000"); salary_map.put("Nina", "$4500"); salary_map.put("Danial", "$400"); salary_map.put("Usman", "$6000"); System.out.println("Displaying Map entries with LinkedHashMap"); System.out.println("\n"); for (Map.Entry<String, String> entry : salary_map.entrySet()) { System.out.println("Employee Name: " + entry.getKey() + " and Salary = " + entry.getValue()); } } } |
You may also notice the order of inserting and iteration is the same in above example. To make it clearer, I am using the same example as above with the exception of using the HashMap instead of LinkedHashMap and see the output:
See online demo and code
The same code with HashMap class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import java.util.*; public class map_demo { public static void main(String[] args) { Map<String, String> salary_map = new HashMap<String, String>(); salary_map.put("Mike", "$5000"); salary_map.put("Nina", "$4500"); salary_map.put("Danial", "$400"); salary_map.put("Usman", "$6000"); System.out.println("Displaying Map entries with HashMap"); System.out.println("\n"); for (Map.Entry<String, String> entry : salary_map.entrySet()) { System.out.println("Employee Name: " + entry.getKey() + " and Salary = " + entry.getValue()); } } } |
You can see the difference; the iteration order is different as compared to insertion order.
An example of using the iterator object
Rather than using the for loop, you may use iterator object with the while loop to iterate through the Map object.
See this example where I have created a Map object with name/salary pairs. After that, an iterator object is created and while loop is used to display the Map pairs:
See online demo and code
The code with iterator object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import java.util.*; public class map_demo { public static void main(String[] args) { Map<String, String> salary_map = new LinkedHashMap<String, String>(); salary_map.put("Mike", "$5000"); salary_map.put("Nina", "$4500"); salary_map.put("Danial", "$400"); salary_map.put("Usman", "$6000"); System.out.println("Displaying Map key/value pairs:"); Iterator<Map.Entry<String, String>> map_iterator = salary_map.entrySet().iterator(); String str=""; while (map_iterator.hasNext()) { Map.Entry<String, String> pair = map_iterator.next(); str += pair.getKey() +"\t" +pair.getValue() + "\n"; } System.out.println(str); } } |
A demo of Map clear() method
The clear() method of Map interface can be used for removing all key/value pairs from the specified Map.
In this example, a Map is created with a few pairs. The Map entries are displayed before and after using the clear() method so you may see the difference:
See online demo and code
The code before and after using the clear Map method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import java.util.*; public class map_demo { public static void main(String[] args) { Map<String, Integer> tel_dir_map = new HashMap<String, Integer>(); tel_dir_map.put("Mike", 4567891); tel_dir_map.put("Nina", 1424541); tel_dir_map.put("Danial", 45678977); tel_dir_map.put("Usman", 14712314); System.out.println("The Map before clear method:"); System.out.print("\t" + tel_dir_map); tel_dir_map.clear(); System.out.print("\n"); System.out.print("\n"); System.out.println("The Map before after clear() method:"); System.out.print("\t" + tel_dir_map); } } |
You see, an empty Map is displayed after using the clear() method.
Accessing the value of a key by using Map get method
By using the get() method of Map, the value of a key can be accessed. The get() method takes the key and returns the value associated with that key. If the key is not found, the null is returned.
If the key is not found, the null is returned. The demonstration is shown below where you are asked to enter a name. If you enter the name that exists in the Map, the corresponding number will display.
If you enter some other name the null will be returned:
See online demo and code
The code that takes user input and Map’s get() method will return the value of key:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.*; import java.util.Scanner; public class map_demo { public static void main(String[] args) { Map<String, Integer> tel_dir_map = new HashMap<String, Integer>(); tel_dir_map.put("Mike", 4567891); tel_dir_map.put("Nina", 1424541); tel_dir_map.put("Danial", 45678977); tel_dir_map.put("Usman", 14712314); System.out.println("Enter Name (Mike, Nina, Danial, Usman): "); Scanner scanner = new Scanner(System.in); String Str_name = scanner.nextLine(); System.out.println("The Number of " + Str_name + ": " + tel_dir_map.get(Str_name)); } } |
An example of using the remove method
The remove() method can be used for deleting a specified entry from the given Map. The remove method takes the key as a parameter.
In the following demo, the Map is displayed before using the remove() method. Again, the user is asked to enter a key to be removed from the Map. If you enter a key from the displayed options, the map will display again after removing that key.
If you enter some other key that does not exist, the map will still display with all four key/value pairs:
See online demo and code
The code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import java.util.*; import java.util.Scanner; public class map_demo { public static void main(String[] args) { Map<String, Integer> tel_dir_map = new HashMap<String, Integer>(); tel_dir_map.put("Mike", 4567891); tel_dir_map.put("Nina", 1424541); tel_dir_map.put("Danial", 45678977); tel_dir_map.put("Usman", 14712314); System.out.println("The Map before remove method:"); System.out.print("\t" + tel_dir_map); System.out.print("\n"); //User inout for the key to be removed from Map System.out.println("Enter a Key from: (Mike, Nina, Danial, Usman) "); Scanner scanner = new Scanner(System.in); String Str_name = scanner.nextLine(); tel_dir_map.remove(Str_name); System.out.println("The Map after remove method:"); System.out.print("\t" + tel_dir_map); } } |
Know the size of specified map by size() method
The size() method can be used to return the number of key/value pairs in the given map. The following example shows that:
See online demo and code
The code of using the size() method in Java map:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.util.*; import java.util.Scanner; public class map_demo { public static void main(String[] args) { Map<Integer, String> fruit_map = new HashMap<Integer, String>(); fruit_map.put(1, "Apple"); fruit_map.put(2, "Mango"); fruit_map.put(3, "Banana"); fruit_map.put(4, "Pine"); fruit_map.put(5, "Apple"); fruit_map.put(6, "Mango"); fruit_map.put(7, "Orange"); System.out.print("The size of map is: " + fruit_map.size()); } } |
The put and putAll methods
You may be surprised to see the put method at the last part of this tutorial. This is because; the put method is used in each example of this tutorial. As the name of method suggests, the put method adds a key/value pair in the specified map.
- It will overwrite the value if a key is re-entered with a new value.
- The putAll method will insert all key/value pairs from one map to this map.