Java Map Interface


Maps are associative collections in Java. Every element in a map is treated as a value and the position of the value is denoted by a key. Therefore, each value key pair is treated as an entry in the map. Every key is unique in a map and it dictates the position of the element stored in it. All traversal techniques, searching, sorting, or updating elements in a map use the keys as references. The two map interfaces in Java are Map and Sorted Map. These interfaces combined have three classes namely HashMap, LinkedHashMap, and TreeMap.

Map Classes

HashMapIn a HashMap structure, the map elements are not maintained in order. To traverse this type of a map, you will have to convert it into either a keySet() or entrySet().
LinkedHashMapA Linked HashMap maintains insertion order and is another implementation of the Map interface.
TreeMapThe TreeMap is a combination of both the Map as well as the SortedMap. In this map, the values are sorted in ascending order and the keys are thereafter ordered.


Some Map Interface Methods

put(Object key, Object value)This method is used to insert new elements into the map
void putAll(Map map)This method is used to insert a map (all elements) in another map.
putIfAbsent(K key, V value)The value specified along with the key is inserted into the map.
remove(Object Key)Used to remove an element from the specified key.



import java.util.*;
class DemoMap
public static void main ( String args [] )
Map < Integer,String > map = new HashMap < Integer,String > ();
map.put( 100,"Amit" );
map.put( 101,"Vijay" );
map.put( 102,"Rahul" );
 //Elements can traverse in any order.
for (Map.Entry m:map.entrySet())
System.out.println( m.getKey()+" "+m.getValue() );



102 Rahul
100 Amit
101 Vijay

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.