Map Interface in Java With Program Example

The Map interface is part of Collection framework, however, it is not a sub-interface of the collection. It deals with and represents a group of objects in key-value pair. In this, keys and values are objects where keys must be unique and values can be duplicated. Each key-value pair is termed as Entry and a set of such entries is known as Map.

Collection Framework

It can be defined as an interface that empowers to store and fetch elements based on a key where a key can not be duplicated and can refer to at most a single value.
Map interface consists its various methods to operate with data. There are more often used methods such as put() method to add an element in a key-value pair, get() method to fetch data based on a key and, remove() method to remove an element.

Point to Remember

1) A map represents data structure that stores data in key-value pair
2) It doesn’t allow duplicate key
3) A key can only be associated to at most single value
4) It accepts null key. Only TreeMap implementation doesn’t allow null

How to create a Map Object?

Map is an interface and its implementation classes can be used to create its object. In below example, we’ve used HashMap.

Map<K,V> map = new HashMap<>();

Method of Maps

MethodExplanation
put(key,value)It adds elements in key value form where key represents identifier and value is the actual data. If one tries to make a duplicate entry, then the old value will be replaced with new one. And returns old data, otherwise null will be returned.
putAll(Map Obj)It adds all the given map data to the calling Map with the same key-value mapping
clear()It clears the map and removes all the enteries
containsKey(key)It check whether the given key present in the map or not, if yes , it would return true otherwise false
containsValue( value)It returns true, if the given value is present with one or more key mappings
entrySet()It returns a Set object representing key-value elements
forEach(action)It enables to iterate key-value enteries one by one until all the enteries iterated
get(key)It returns value associated with the provided key
getOrDefault( key, defaultValue)It returns value associated with the provided key, if it's not present, the provided default value would be returned
isEmpty()It checks whether the given map is empty or not
keySet()It is used to get list of keys present in the map
putIfAbsent(key, value)It adds an element if the given key is not associated with any value in the map and returns null, otherwise existing key value
remove(key)It removes a key-value mapped with the given key
remove( key, value)It removes an entry, provided with the given associated key mapped with the given value only
replace(key, value)It replaces the existing mapping if the given key having a mapping in a map
replace(key, oldValue, newValue)It replaces the existing mapping with the mentioned key, if the targeted key having the old value mapped to it
size()It returns the size of enteries in a map
values()It returns collection object containing all the values in a map

Java Program to demonstrate the basic operations of Map interface

Program:

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapExample {
    public static void main(String[] args) {
        // Creating a Map object
        Map<String,String> map  = new HashMap<>();

        // putting enteries in the map
        map.put("p","programmerbay");
        map.put("e","Example");
        map.put("a","Another");

        // Retrieving an element based on a key
        System.out.println("fetching value associated with p "+map.get("p"));


        // Iterating over Map elements

        Set<Map.Entry<String,String>> enteries = map.entrySet();

        for (Map.Entry<String,String> singleEntry:
             enteries) {
            System.out.println(singleEntry);
        }
    }
}

Output:

fetching value associated with p programmerbay
p=programmerbay
a=Another
e=Example

Implementing Classes and Interfaces of Map

There are various implementation classes and sub interfaces of Map interface.

Below are the following sub interfaces:

1) SortedMap

SortedMap is a sub interface of Map that provides a way to specify ordering on its keys. By default, keys are sorted in natural order. Further, with the help of Comparator, one can also specify custom sorting order. Additionally, keys inserted must implement Comparable interface.

2) NevigableMap

NavigableMap extends SortedMap that provides navigation methods to navigate through entries of a Map. Methods like lowerEntry, ceilingEntry, lowerKey, floorKey and higherKey are used for locating entries in a map.

Similar to NavigableSet, NavigableMap can also be traversed in both ascending or descending key order. However, if one considers performance, then ascending operations are faster than descending ones.

Below are the following implementation classes:

1) HashMap

HashMap provides a hash table based implementation to store data in key-value pair. It accepts a single null key and multiple null values. It doesn’t guarantee the order of a map. It uses a hash function to calculate the hash code, based on which the respective element get stored among the buckets. As a result, it serves constant-time performance for operations like adding and fetching data.

2) LinkedHashMap

LinkedHashMap is a subclass of HashMap that represents Hash table and linked list as its underlying data structure. It preserves the order of entries which is maintained and defined by a doubly linked list. In other words, it fetches elements in the same order in which they are previously added. It permits at most one null key.

3) IdentityHashMap

IdentityHashMap is an implementation class of Map interface that uses Hash Table as its underlying data structure. Unlike HashMap, it uses == operator to identify duplicate entries.

4) WeakHashMap

WeakHashMap is a Hash table based implementation where entries get automatically cleaned up by garbage collector when its key reference for a mapped value is no longer exist or in use.

5) TreeMap

TreeMap is a red-black tree based implementation class of Map interface. It stores elements in some specific order of its key. It doesn’t allow null key.

Basic Operations in Map

There are various operations that can be performed on data. Below are some frequently used operations.
1) Adding elements
2) Updating elements
3) Removing elements
4) Iterating over elements
5) Retrieving element

1) Adding elements

put() and putIfAbsent() method can be used to add element in a map. Both methods are used in different situations
put(k,v) : It adds single element to a given map. It returns null, indicating that no key mapping is exist
putAll(Map obj) : It adds all the elements consisting in passed Map Object.
putIfAbsent(k,v) : It is similar to put() method but only adds elements if the given key mapping is not present in the targeted map

Program:

import java.util.HashMap;
import java.util.Map;

public class MapExample {
public static void main(String[] args) {
// Creating a Map object
Map<String,String> map = new HashMap<>();
// putting entries in the map
map.put("p","programmerbay");

// Printing Map elements
System.out.println(map);


Map<String,String> differentMap = new HashMap<>();
differentMap.put("e","example");

// Adding element to Map elements
map.putAll(differentMap);

// Printing Map elements
System.out.println(map);

// putIfAbsent is used to add element
map.putIfAbsent("c","code ");

// Printing Map elements
System.out.println(map);

}
}

Output:

{p=programmerbay}
{p=programmerbay, e=example}
{p=programmerbay, c=code , e=example}

2) Updating elements

put() is also used to update the existing key mapping in a map. It returns old key-value existing mapping if present in the map, otherwise, null. In other words, put() replaces an entry if passed key already is present, otherwise, add-operation is performed.

Program:

import java.util.HashMap;
import java.util.Map;

public class MapExample {
public static void main(String[] args) {
// Creating a Map object
Map<String,String> map = new HashMap<>();
// putting entries in the map
map.put("p","programmerbay");

System.out.println(map);

// updating existing key
map.put("p","updated");

System.out.println(map);

}
}

Output:

{p=programmerbay}
{p=updated}

3) Removing elements

remove() method is used to delete a key value pair from a map. There are various overloaded methods of remove.
remove(k) : It removes a key-value mapped with given key in a map
remove(k,v) : It removes a key-value pair present that matches with provided key and value.

Program:

import java.util.HashMap;
import java.util.Map;

public class MapExample {
public static void main(String[] args) {
// Creating a Map object
Map<String,String> map = new HashMap<>();
// putting entries in the map
map.put("p","programmerbay");

System.out.println(map);

// remove existing key
map.remove("p","programmerbay");

System.out.println(map);

}
}

Output:

{p=programmerbay}
{}

4) Iterating over elements

Enhanced forEach() can be used to iterate over elements. In order to iterate through a map, first one needs to get its all entries using entrySet() method.

Program:

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapExample {
    public static void main(String[] args) {
        // Creating a Map object
        Map<String,String> map  = new HashMap<>();
        // putting entries in the map
        map.put("p","programmerbay");
        map.put("c","code");
        map.put("e","example");



        Set<Map.Entry<String,String>> enteries = map.entrySet();

        for (Map.Entry<String,String> singleEntry:
             enteries) {
            System.out.println(singleEntry);
        }
    }
}

Output:

p=programmerbay
c=code
e=example

 

5) Retrieving element

get() method is used to retrieve value associated with a key. It accepts key name based on which the associated value is retrieved.

Program:

import java.util.HashMap;
import java.util.Map;

public class MapExample {
    public static void main(String[] args) {
        // Creating a Map object
        Map<String,String> map  = new HashMap<>();
        // putting entries in the map
        map.put("p","programmerbay");

        System.out.println(map);

        // diplaying value based on key
        System.out.println(map.get("p"));

    }
}

Output:

{p=programmerbay}
programmerbay

 

 

 

Leave a Reply