Java Map Part I

Java Map is an object that maps keys to values, or is a collection of attribute-value pairs. It models the function abstraction in mathematics.

 

Note that a Map is not considered to be a true collection, as the Map interface does not extend the Collection interface. Instead, it starts an independent branch in the Java Collections Framework

 

A Map cann’t contain duplicate keys and each key can map to at most one value. Some implementations allow null key and null value (HashMap and LinkedHashMap) but some does not (TreeMap).The order of a map depends on specific implementations, e.g TreeMap and LinkedHashMap have predictable order, while HashMap does not

 

Why and When Use Maps:

Maps are perfectly for key-value association mapping such as dictionaries. Use Maps when you want to retrieve and update elements by keys, or perform lookups by keys. Some examples:

  • A map of error codes and their descriptions.
  • A map of zip codes and cities.
  • A map of managers and employees. Each manager (key) is associated with a list of employees (value) he manages.
  • A map of classes and students. Each class (key) is associated with a list of students (value).

This tutorial provides code examples around the three major implementations of Map which are described below.

 

 Creating a new Map

Creating a HashMap:Always use interface type (Map), generics and diamond operator to declare a new map. The following code creates a HashMap:

1
2
3
4
5
6
7
8
Map<Integer, String> mapHttpErrors = new HashMap<>();
mapHttpErrors.put(200, "OK");
mapHttpErrors.put(303, "See Other");
mapHttpErrors.put(404, "Not Found");
mapHttpErrors.put(500, "Internal Server Error");
System.out.println(mapHttpErrors);

This maps HTTP status codes to their descriptions. Output:

1
{404=Not Found, 500=Internal Server Error, 200=OK, 303=See Other}

As you can see in the output, a HashMap does not impose any order on its key-value elements.You can create a new Map that copies elements from an existing map. For example:

1
Map<Integer, String> mapErrors = new HashMap<>(mapHttpErrors);

The map mapErrors is created with initial elements copied from the map mapHttpErrors. Creating a LinkedHashMap:The following code creates a LinkedHashMap that maps phone numbers with contact names:

1
2
3
4
5
6
7
8
Map<String, String> mapContacts = new LinkedHashMap<>();
mapContacts.put("0169238175", "Tom");
mapContacts.put("0904891321", "Peter");
mapContacts.put("0945678912", "Mary");
mapContacts.put("0981127421", "John");
System.out.println(mapContacts);

Output:

1
{0169238175=Tom, 0904891321=Peter, 0945678912=Mary, 0981127421=John}

As you can see, the LinkedHashMap maintains its elements by their insertion order. Creating a TreeMap:The following code creates a TreeMap that maps file extensions to programming languages:

1
2
3
4
5
6
7
8
9
10
11
Map<String, String> mapLang = new TreeMap<>();
mapLang.put(".c", "C");
mapLang.put(".java", "Java");
mapLang.put(".pl", "Perl");
mapLang.put(".cs", "C#");
mapLang.put(".php", "PHP");
mapLang.put(".cpp", "C++");
mapLang.put(".xml", "XML");
System.out.println(mapLang);

Output:

1
{.c=C, .cpp=C++, .cs=C#, .java=Java, .php=PHP, .pl=Perl, .xml=XML}

As you can see, the TreeMap sorts its keys by their natural ordering, which is the alphabetical order in this case.

Performing Basic Operations on a Map

The basic operations of a Map are association (put), lookup (get), checking (containsKey and containsValue), modification (remove and replace) and cardinality (size and isEmpty). Associating a value with a key:The put(K, V) method associates the specified value V with the specified key K. If the map already contains a mapping for the key, the old value is replaced by the specified value:

1
2
3
4
5
6
Map<Integer, String> mapHttpErrors = new HashMap<>();
mapHttpErrors.put(400, "Bad Request");
mapHttpErrors.put(304, "Not Modified");
mapHttpErrors.put(200, "OK");
mapHttpErrors.put(301, "Moved Permanently");
mapHttpErrors.put(500, "Internal Server Error");

Getting a value associated with a specified key:The get(Object key) method returns the value associated with the specified key, or returns null if the map contains no mapping for the key. Given the map in the previous example:

1
2
String status301 = mapHttpErrors.get(301);
System.out.println("301: " + status301);

Output:

1
301: Moved Permanently

Checking if the map contains a specified key:The method containsKey(Object key) returns true if the map contains a mapping for the specified key. For example:

1
2
3
if (mapHttpErrors.containsKey("200")) {
    System.out.println("Http status 200");
}

Output:

1
Found: Http status 200
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: