Introduction to Map and SortedMap Interface

Map Interface:
A Map is an object that maps keys to
values. It is not an extension of the collection interface rather it has own
interface hierarchy. Map provides a more general
way for storing elements without containing duplicate keys.
It allows you to store pairs of elements, termed "keys" and
"values", where each key maps to one value. Thus the
keys in a map must be unique.
The Map interface methods can be broken down into three
sets of operations:
Altering: The alteration operations allow you to
add and remove key-value pairs from the map. Both the key and value can be null.
Querying: The query operations allow the user to
retrieve key/value pairs from the Map.
Providing alternative views: This method allow you to work with the different
views which can be used to analyze Map key/value Objects.
Map Methods Returning
Views:
These methods return objects
which allow you to traverse the elements of the Map, and also delete elements
from the Map.
|
Method
|
Uses
|
|
entrySet()
|
Returns a Set
view of the mappings contained in the map. Each element in the set is a
Map.Entry object which can have it's key and value elements accessed
with getKey() and getValue() methods (also has a setValue() method) |
| keySet() |
Returns a Set
view of the keys contained in the map. Removing elements from the Set
will also remove the corresponding mapping (key and value) from the Map |
| values() |
Returns a
Collection view of the values contained in the map. Removing elements
from the Collection will also remove the corresponding mapping (key and
value) from the Map |
Map.Entry Interface:
Each element is 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 Collections Framework provides three
general-purpose Map implementation:
HashMap
TreeMap
LinkedHashMap
HashMap:
The HashMap is a class which is used to perform some basic operations
such as inserting, deleting, and locating elements in a Map
. The java.util.HashMap class is
implemented with and roughly equivalent to a Hashtable except that
it is unsynchronized and permits null. It works with the Iterators requires
a well-defined implementation of the method hashCode( ).
TreeMap:
The TreeMap implementation is useful when you need to traverse the
keys from
a collection in a sorted manner. The elements added to a TreeMap must be sortable in
order to work properly. It is depend upon the size of the specified collection,
it may be faster to add elements to a HashMap , then convert the map to a
TreeMap for traversing the sorted keys.
LinkedHashMap:
A LinkedHashMap is implemented using both Hash
table and linked list implementation of the Map interface. This
implementation differs from HashMap that maintains a doubly-linked list
running through all of its entries in it. The orders of its elements are based on the order in which they were inserted into the set (insertion-order).
The list of methods supported by Map interface are shown in the table given below:
|
Method
|
Uses
|
|
put(Object
key, Object value)
|
Associates the specified value with the specified key
in the map.
|
|
clear(
)
|
Removes all mappings from the map
|
|
putAll(Map t)
|
Copies all of the mappings from the specified map to
the map.
|
|
isEmpty(
)
|
Returns true if this map contains no key-value mappings.
|
|
iterator(
)
|
Returns an
Iterator object for the
collection which may be used to retrieve an object.
|
|
remove(Object key)
|
Removes the mapping for this key from this map if it is present.
|
|
keySet( )
|
Returns a set view of the keys contained in this map.
|
|
entrySet( )
|
Returns a set view of the mappings contained in this map.
|
|
values( )
|
Returns a collection view of the values contained in this map.
|
|
size(
)
|
Returns the number of key-value mappings in this map.
|
SortedMap Interface:
The
Collection Framework provides a special Map interface for maintaining elements
in a sorted order called SortedMap .
The SortedMap interface extends the Map interface which maintains its elements in ascending
order. Working with
a SortedMap is
just similar to a SortedSet except, the sort is done on the map keys. In addition to methods
of the Map interface, it provides two methods shown as:
firstKey( )
lastKey( )
The firstKey( ) method returns the first (lowest)
value currently in the map while the lastKey( ) method returns the
last (highest) value currently in the map.
Let see an example implementing the HashMap and
TreeMap
class.
import java.util.*;
public class MapDemo {
public static void main(String args[]) {
String days[]={"Sunday", "Monday", "Tuesday", "Wednesnday",
"Thursday", "Friday", "Saturday"};
Map<Integer, String> map = new HashMap<Integer, String>();
try{
for(int i=0; i<7; i++){
map.put(i, days[i]);
}
TreeMap<Integer, String> tMap=new TreeMap<Integer, String>(map);
//Rerieving all keys
System.out.println("Keys of tree map: " + tMap.keySet());
//Rerieving all values
System.out.println("Values of tree map: " + tMap.values());
//Rerieving the First key and its value
System.out.println("First key: " + tMap.firstKey() +
" Value: " + tMap.get(tMap.firstKey()) + "\n");
//Removing the first key and value
System.out.println("Removing first data: "
+ tMap.remove(tMap.firstKey()));
System.out.println("Now the tree map Keys: " + tMap.keySet());
System.out.println("Now the tree map contain: " + tMap.values() + "\n");
//Rerieving the Last key and value
System.out.println("Last key: " + tMap.lastKey() +
" Value: " + tMap.get(tMap.lastKey()) + "\n");
//Removing the last key and value
System.out.println("Removing last data: " + tMap.remove(tMap.lastKey()));
System.out.println("Now the tree map Keys: " + tMap.keySet());
System.out.println("Now the tree map contain: " + tMap.values());
}
catch(Exception e){}
}
}
|
Output of this program:
C:\nisha>javac MapDemo.java
C:\nisha>java MapDemo
Keys of tree map: [0, 1, 2, 3, 4, 5, 6]
Values of tree map: [Sunday, Monday, Tuesday, Wednesnday, Thursday, Friday, Saturday]
First key: 0 Value: Sunday
Removing first data: Sunday
Now the tree map Keys: [1, 2, 3, 4, 5, 6]
Now the tree map contain: [Monday, Tuesday, Wednesnday, Thursday, Friday, Saturday]
Last key: 6 Value: Saturday
Removing last data: Saturday
Now the tree map Keys: [1, 2, 3, 4, 5]
Now the tree map contain: [Monday, Tuesday, Wednesnday, Thursday, Friday]
C:\nisha>
|
The given program stores the values mapping with their
keys to the map. The keySet( ) method retrieves all keys from the map and the
values( ) method retrieves all the values added to a map. The remove(
) method removes the key from the map with its value specified in it.
Download this Program:

|