Friday, Jan 19th

Last update12:59:40 PM GMT

Map

Write e-mail

Map data structure in Java is used to map keys to values, that is, one to one object relationship. A map can’t have duplicate keys, and each key can point to only one object or value. So, like if we want to store the information of employee with employee id and employee name. We know that employee name can’t be unique but employee id is, we can have the map as (employee id, employee name). Let’s learn the basic syntax for declaring Map and using it. And please don’t worry about HashMap, which is an implementation of the interface Map, since we will cover it later.

argaiv1868

Map<String, String> countryCodes = new HashMap<String, String>(); // collections with generics, OR
Map countryCodes = new HashMap ();                                // collections without generics
 
countryCodes.put(“IN”, “India”);
countryCodes.put(“US”, “United States of America”);
countryCodes.put(“UK”, “United Kingdom”);
countryCodes.put(“GR”, “Germany”);

Now the way to retrieve a value corresponding to a key, is:

String countryName = countryCodes.get(“IN”);          // if generics used, OR
String countryName = (String)countryCodes.get(“IN”);  // if generics not used

The basic operations provided by Map interface:

  • Object put(Object key, Object value)
  • Object get(Object key)
  • Object remove(Object key)
  • boolean containsKey(Object key)
  • boolean containsValue(Object value)
  • int size()
  • boolean isEmpty() 

The bulk operations provided by Map interface:

  • void putAll(Map t)
  • void clear()

There are three collection views provided by Map interface, and following are the methods used for obtaining the same:

  • Set keySet(): The object of the type Set, which provides the set of values of the Map keys. Why Set, since we have the unique values of keys!
  • Collection values(): The collection of values, which can be cast to any Collection implementation.
  • Set entrySet(): Set of objects implementing Map.Entry interface. We will just discuss the Map.Entry interface. 

Each element in a map has a key and value. Each key-value pair is saved in a java.util.Map.Entry object. A set of these map entries can be obtained by calling a map's entrySet() method. Iterating over a map is done by iterating over this set. The methods provided by this interface are:

  • getKey() – returns the key form the pair
  • getValue() – returns the value form the pair
  • setValue(Object value) – sets the value of the pair. But this method is not supported by all Map.entry objects.

Share this post



Add comment

Please refrain from using slang or abusive language in the comments.
To avoid waiting for your comment to be published after being reviewed, please log in as a registered user.


Security code
Refresh

Web Hosting