Java Collections - Giving Keys and Values using the Map Interface

Guest Posts Paolo Nikko Nuñal

For those of you who have been programming in PHP, you might have been lucky enough to enjoy the many methods and functions it has to offer most especially when it comes to dealing with arrays. One such example is using the associative array in which you can actually provide keys and values. In Java, you can also do the same using the Map interface.

The Map interface gets the value and key making it easy for you to set a specific object and corresponding value that you want to get it from the map.

import java.util.*;

public class MapDemo
 public static void main(String args[])
 Map mp = new HashMap();
 mp.put("John", 12);
 mp.put("Joe", 41);
 mp.put("July", 24);
 System.out.print("Contents of Map: " + mp);
 System.out.println("Age of Jake is: " +mp.get("Jake"));
 System.out.println("Remove July: " +mp.remove("July"));
 System.out.print("Contents of Map: " + mp);

From our example above we have created a Map object. We then added four elements each with their own corresponding keys and data. After which we illustrate what the contents of the map where. We then try to look for a specific object, in our example we searched Jake to get the value of it which is 13. The next example removed an object using the name and in our case "July".

You can use the Map interface for a wide variety of uses as it can easily help you out in "mapping" objects easily and associating them with "keys". For the complete methods of the Map interface you can check it out here.