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 the Dictionary abstract class.
- The Map object stores the data in the key–value pairs.
//Create a map Map<String, Integer> tel_dir_map = new HashMap<String, Integer>(); //Add elements by ‘put‘ method tel_dir_map.put("Mike", 4567891); //Retrieved by ‘get‘ method int value = tel_dir_map.get("Mike"); //Number of key-value pairs by ‘size’ int map_size = tel_dir_map.size();
- 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 the longer term, unlike arrays, sets, or lists whose index is based on numeric values.
- As the Map is an interface, this is implemented by a few classes. These classes include:
- HashMap
- TreeMap
- 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.
An example of creating a Java Map with HashMap
In this example, a map object is created with the HashMap class.
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:
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); } }
Output:
{Mike=4567891, Danial=45678977, Nina=1424541, Usman=14712314}
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 from 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.
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:
The code of creating the map with LinkedHashMap:
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()); } } }
Output:
Employee Name: Nina and Salary = $4500
Employee Name: Danial and Salary = $400
Employee Name: Usman and Salary = $6000
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:
The same code with HashMap class:
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()); } } }
Output:
Displaying Map entries with HashMap
Employee Name: Mike and Salary = $5000
Employee Name: Danial and Salary = $400
Employee Name: Nina and Salary = $4500
Employee Name: Usman and Salary = $6000
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:
The code with iterator object:
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); } }
Output:
Nina $4500
Danial $400
Usman $6000
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:
The code before and after using the clear Map method:
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); } }
Output:
{Mike=4567891, Danial=45678977, Nina=1424541, Usman=14712314}
The Map before after clear() method:
{}
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.
- 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:
- The code that takes user input and Map’s get() method will return the value of the key:
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)); } }
Sample Output:
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 all four key/value pairs:
The code:
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); } }
Sample output:
Know the size of the 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:
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()); } }
Output:
The put and putAll methods
You may be surprised to see the put method in the last part of this tutorial. This is because; the put method is used in each example of this tutorial.
As the name of the 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.