Java Map Interface

tutorial and example
tutorial and example

JAVA MAP INTERFACE

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs.

  • HashMap: HashMap stores the keys in a hash table. It uses the hashCode() method of the keys to retrieve their value efficiently. The benefit is that the storing and retrieving of the values by key have constant time. The disadvantage is that we lose the order of the insertion.
  • TreeMap: TreeMap stores the key in sorted tree structure. The benefit is that the key are always in sorted order but adding and checking of elements by the key takes longer time O(log n).
  • Hashtable: Hashtable is an array of list. Each list is known as a bucket. The position of bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key. It contains only unique elements. It does not allow null key or value. It is synchronized.

Useful Methods

Modifier and Type

Method

Description

void

clear()

It removes all keys and values from the map.

boolean

isEmpty()

It returns whether the map is empty.

int

size()

It returns the number of entries (key/value pairs) in the map.

V

get(Object key)

It returns the value mapped by key or null if none is mapped.

V

put(K key, V value)

It adds or replaces key/value pair. Returns previous value or null .

V

remove(Object key)

It removes and returns value mapped to key. Returns null if none.

boolean

containsKey(Object key)

It returns whether key is in map.

boolean

containsValue(Object)

It returns value is in map.

Set<K>

keySet()

It returns set of all keys.

Collection<V>

values()

It returns Collection of all values.

Example

output:

Example: TreeMap

Output:

Example: HashTable

Output: