map interface

Java Map Interface, Implementations and Example

A Map interface is an object that maps keys to values or handles key-value pairs. It cannot contain duplicate keys and each key can map to at most one value.

Map interface hierarchy

map interface

The Map interface Java SE

The methods of “Map” interface for basic operations, bulk operations and collection views are listed below for your reference.

“SortedMap” interface

A “Map” interface that maintains its mappings in ascending key order is called the SortedMap interface. This is the Map analog of SortedSet. It extends “Map” interface.

Sorted maps are used for naturally ordered collections of key or value pairs, such as dictionaries and telephone directories.

“NavigableMap” interface

NavigableMap interface is an extension of SortedMap interface which provides popular navigation methods like lowerEntry, floorEntry, ceilingEntry, higherEntry etc., that returns the closest matching results for the given search targets. It extends SortedMap interface

Implementations of “Map” interface

The three general-purpose implementations of the Map interface are:

  • HashMap: Hash table based implementation of the “Map” interface. It permits null values and the null key. Use this class if you want maximum speed and do not want to care about iteration order. It is most commonly used implementation.
  • TreeMap: A Red-Black tree based NavigableMap implementation. TreeMap is sorted according to the natural ordering of its keys. Use this class when you need SortedMap operations or key-ordered Collection-view iteration.
  • LinkedHashMap: Hash table and linked list implementation of the Map interface. Although it is somewhat slower than HashMap for adding and removing elements, you can expect faster iteration with a LinkedHashMap.

Example: “Map” Interface

Note:

  • Map.entrySet method returns a collection-view of the map.
  • Map.Entry<Integer, String> is a map entry i.e., key-value pair

Output

Related Posts

Reference

Leave a Reply

avatar
  Subscribe  
Notify of