Java map interface – Java Map Interface with Example | Basic & Bulk Operations of Map Interface in Java | Map Methods

Java map interface: Java Map Interface Tutorial presents you with the ultimate learnings about the concept. Map Interface in Java offers methods for storing values based on a key basis. Learn thoroughly about Methods of Map interface, Methods of Map.Entry Interface from our tutorial and also you can get a good grip on Java Map Implementations and Map Interface Basic Operations & Bulk Operations.

This Comprehensive Java Map Interface Tutorial Covers:

Java Map Interface

Java maps tutorial: A map in Java is an object that stores the data in between keys and values or key/values pairs. Keys and values both are objects. A map contains a unique key but values may be duplicated. There is one key point about maps that are important to mention at the outset; they don’t implement the collection interface.

The map interface maps the unique key to values. A key is an object that is used to retrieve a value at a later date. If you have a key and a value then you can store the value in the map object. After the value is stored, you can retrieve it by using its key.

Also Check: HashSet Class in Java with Example

Java Map Hierarchy

Java map examples: There are two interfaces for implementing a Map in Java are Map and SortedMap, and three classes these classes are HashMap, LinkedHashMap, and TreeMap.

Java Map interface with Example 1

Why We Use Maps Interface in Java?

Java util map example: if we want to store the data in keys and values or key/values pair then we should go for maps. Some examples are:

  1. A map of pin code and cities.
  2. A map of student roll no: and student marks.
  3. A map of employee address and employee mobile no:
  4. A map of universities and professors.

Java Map Implementations

Map interface in java: As Map is an interface you have to instantiate a particular implementation of the Map interface to utilize it. The Java Collections API includes the resulting Java Map Implementations:

java.util.HashMap
java.util.Hashtable
java.util.EnumMap
java.util.IdentityHashMap
java.util.LinkedHashMap
java.util.Properties
java.util.TreeMap
java.util.WeakHashMap

The most commonly used Map implementations are HashMap and TreeMap.

HashMap maps a key and a value but it doesn’t prove any order of the elements saved internally in the map. TreeMap also maps a key and a value. Moreover, it proves the order in which keys or values are repeated- which is the sort order of the keys or values. The most efficient map implementation among both is HashMap.

Do Refer: Vector in Java with Example

Implementation of Map Interface

Java map implementations: In this section of the java map tutorial, you will be studying & getting some knowledge on the Implementation of HashMap Class and TreeMap Class.

1. Implementing HashMap Class

implementation of hashmap example

Output:

Map: {One=1, Two=2}
Keys: [One, Two]
Values: [1, 2]
Entries: [One=1, Two=2]
Removed Value: 2

2. Implementing TreeMap Class

TreeMap Implementation example
Output:

Map using TreeMap: {First=1, Second=2}
New Map: {First=11, Second=22}
Removed Value: 11

Create a Map Interface

In order to create a Java Map, first, you should create an example of one of the classes that implement the Java map interface. Below, we have shared two examples of how to create a Map using map implementations.

Map mapA = new HashMap();

Map mapB = new TreeMap();

Map.Entry Interface

In Java Map Interface, Entry is the subinterface of Map. We will access it by ‘Map.Entry’ as it is used to return a collection-view of the map if elements are of this class. Also, it is helpful in providing map methods to get key and value.

Methods of Map.Entry Interface

Method Description
K getKey() It is used to obtain a key.
V getValue() It is used to obtain value.
int hashCode() It is used to obtain hashCode.
V setValue(V value) It is used to replace the value corresponding to this entry with the specified value.
boolean equals(Object o) It is used to compare the specified object with the other existing objects.
static <K extends Comparable<? super K>,V> Comparator<Map.Entry<K,V>> comparingByKey() It returns a comparator that compares the objects in natural order on key.
static <K,V> Comparator<Map.Entry<K,V>> comparingByKey(Comparator<? super K> cmp) It returns a comparator that compares the objects by key using the given Comparator.
static <K,V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() It returns a comparator that compares the objects in natural order on value.
static <K,V> Comparator<Map.Entry<K,V>> comparingByValue(Comparator<? super V> cmp) It returns a comparator that compares the objects by value using the given Comparator.

Map Interface Basic Operations

put, get, containsKey, containsValue, size, and isEmpty are the Map Interface Basic Operations that behave precisely similar to their counterparts in Hashtable.

Map Interface Bulk Operations

The clear operation does correctly what you would think it could do: It eliminates all the mappings from the Map. The putAll operation is the Map Analogue of the Collection interface’s addAll operation. Besides its prominent use of dumping one Map into another, it has a second, more subtle use. Assume a Map is utilized to describe a collection of attribute-value pairs; the putAll operation, in fusion with the Map conversion constructor, gives an excellent way to perform attribute map creation with default values.

Interfaces that extend Map

The Map Interface is additionally extended by these subinterfaces:

  • SortedMap
  • NavigableMap
  • ConcurrentMap

SubInterfaces of Java Map

Java Map Methods

1. void clear(): This method is used to removes all the key/values pairs from the invoking maps.

2. boolean containsKey(Object k): This method returns true if the invoking map contains k as a key. Otherwise, it returns false.

3. boolean containsValue(Object v): This method returns true if the invoking map contains v as a value. Otherwise, it returns false.

4. boolean equals(Object obj): This method is used to compare the specified object with the map.

5. V get(Object k): This method returns the value associated with the key k and it returns null if the key is not found.

6. int hashCode(): This method returns the hashcode of the invoking maps.

7. boolean isEmpty(): It returns true if the invoking map is empty. Otherwise, it returns false.

8. V put(key K, value V): This method is used to put an entry in this map.

9. void putAll(Map map): It is used to insert the specified maps in this map.

10. V remove(Object k): This method is used to removes the entry whose key equals k.

11. int size(): This method returns the number of key/value pairs in the map.

12. Set keySet(): This method is used to returns the set that contains the keys in the invoking map.

13. Set entrySet(): This method is used to returns a set that contains the entries in the map.

14. Collection values(): This method is used to returns a collection containing the values in the map.

Java Map Interface Example

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

class JavaMapExample{
public static void main(String args[]){

//creating a map
Map<Integer, String> map = new HashMap<Integer, String>();

//adding values in this map
map.put(101, "Rahul");
map.put(102, "Amit");
map.put(103, "Vijay");
map.put(104, "Suresh");
map.put(105, "John");

System.out.println("Map entries are: "+map);

//returns the value associated with the key
System.out.println("getting value is: "+map.get(103));

/*returns true if the invoking map contains k as a key.
Otherwise, it returns false.*/
System.out.println("Check map contains specified key or not: "+map.containsKey(104));

/*returns true if the invoking map contains v as a value.
Otherwise, it returns false.*/
System.out.println("Check map contains specified value or not: "+map.containsValue("Ramesh"));

//returns the number of key/values pair in the map
System.out.println("key/values pair in the map is: "+map.size());

//removes the entry whose key equals to k(105).
System.out.println("Removing entry: "+map.remove(105));

//returns the hashcode of the invoking maps.
System.out.println("The map hash code is: "+map.hashCode());

//return the set that contains the keys in the invoking map
System.out.println("Key set is: "+map.keySet());

//removes all the key/values pairs from the invoking maps.
map.clear();
System.out.println("Removing all entries from map: "+map);

}
}

Output:

Java Map interface with Example 2