AppDividend
Latest Code Tutorials

Java Map Interface Tutorial With Example | Map Interface in Java

0

Java Map Interface Tutorial With Example | Map Interface in Java is today’s topic. A map is an object that is designed to store associations between keys and their corresponding values – or key/value pairs. Both the key and value are objects. Essentially, a key has to be unique, whereas values may not be so. An important thing to note is that maps don’t implement the Iterable interface and therefore, one can not cycle through a map using a for-each style for loop. In Java, one cannot obtain an iterator to a map. However, one can obtain a collection-view of a map which does allow the use of either the for loop or an iterator.

Java Map Interface Tutorial

A map contains values based on the key, i.e., key and value pair.

Each key and value pair is known as the entry. The Map contains the unique keys. The Map is useful if you have to search, update, or delete elements based on the key.

 

Java Map Interface Tutorial

A Map doesn’t allow duplicate keys, but you can have the duplicate values. HashMap and LinkedHashMap allow the null keys and values, but the TreeMap doesn’t allow any null key or value.

A Map can’t be traversed, so you need to convert it into Set using a keySet() or entrySet() method.

Class Description
HashMap HashMap is an implementation of Map, but it doesn’t maintain any order.
LinkedHashMap LinkedHashMap is the implementation of Map. It inherits the HashMap class. It maintains insertion order.
TreeMap TreeMap is an implementation of Map and SortedMap. It maintains an ascending order.

#Map Interfaces

The map interfaces define a character and nature of maps. The following interfaces support maps in Java:

#Map

Maps unique keys to values.

#Map.Entry

An inner class of Map which describes an element (i.e., a key/value pair) in a map.

#SortedMap

Extends Map so that a keys are maintained in the ascending order.

#NavigableMap

Extends SortedMap to handle a retrieval of entries based on closest-match searches.

#Map Interface

The Map interface maps the unique keys to values to make up key/value pairs. A “key” is an object which is primarily used to retrieve a “value” from the map. With a key and a value, one can store the value in a Map object. The map is a generic interface and is declared as:

interface Map <K, V>

Here, K specifies the type of keys, and V specifies the type of values.

Some of the methods declared by Map are following.

#void clear() 

Removes all key/value pairs from a map which calls it.

#boolean containsKey(Object k)

Returns true if the map contains k as a key. Returns false otherwise.

#boolean containsValue(Object v)

Returns true if the map contains v as the value. Returns false otherwise.

#Set<Map.Entry<K,V>>entrySet()

Returns the Set that contains the entries in the map. The set contains objects of the type Map.Entry. Therefore, this method provides a set-view of the invoking map.

#boolean equals(Object obj)

Returns true if obj is the Map and is equal. Returns false otherwise.

#V get(Object k)

Returns value with the associated key k. If no such key is found, returns null.

V put(K k, V v)

Puts an entry in the map and overwrites any previous value associated with the same key. Returns null if the key did not exist earlier. Otherwise, it returns the previous value associated with the key.

#V remove(Object k)

Removes entry corresponding to key k.

#int size()

Returns a number of key/value pairs in the map.

#Implementing the Map Interface

Entry is the subinterface of Map. So we will be accessed by Map.Entry name. It returns the collection-view of the map, whose elements are of this class. It provides the methods to get key and value.

There are several ways to implement and use the map interface. Several classes provide implementations of the Map interface. Some of these classes are following.

#AbstractMap

Implements most of the Map interface.

#EnumMap

Extends AbstractMap to work with enum keys.

#HashMap 

Extends AbstractMap to work with a hash table.

#TreeMap

Extends AbstractMap to work with a tree data structure.

#WeakHashMap

Extends AbstractMap to work with a hash table with weak keys.

#LinkedHashMap

Extends HashMap to work with insertion-order iterations.

#IdentityHashMap

Extends AbstractMap and uses reference equality for comparing documents.

To demonstrate the use of Map interface, consider the following example programs:

import java.util.*;

class MapEx1{
	public static void main(String [] args){
		HashMap<String, Integer> h = new HashMap<String, Integer>();

		h.put("M", new Integer(0));
		h.put("A", new Integer(1));
		h.put("V", new Integer(2));
		h.put("E", new Integer(3));
		h.put("R", new Integer(4));
		h.put("I", new Integer(5));
		h.put("C", new Integer(6));
		h.put("K", new Integer(7));

		Set<Map.Entry<String, Integer>> set0 = h.entrySet();

		for(Map.Entry<String, Integer> a : set0){
			System.out.print(a.getKey() + ": ");
			System.out.println(a.getValue());
		}

		System.out.println();
	}
}

See the following output.

Map Interface

 

Since hashing is used, there is no guarantee in which order the elements will be stored and displayed in output when the above program runs.

#Map.Entry Interface

Several methods in the Map interface throw a ClassCastException when an object is not compatible with the elements in the map. A NullPointerException is thrown if the attempt is made to use a null object and null is not allowed in the map. I have written an article on Exception Handling in Java if you are not familiar with Exception.

Maps revolve around two basic operations: get() and put(). The get() is used to obtain the value passing the key as an argument, and put() is used to put a value in a map by specifying the key and the value.

#Methods of Map.Entry interface

#K getKey()

It is used to obtain a key.

#V getValue()

It is used to obtain a value.

#int hashCode()

It is used to obtain a hashCode.

#V setValue(V value)

It is used to replace a value corresponding to this entry with the specified value.

#boolean equals(Object o)

It is used to compare a specified object with an 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 the natural order on key.

#static <K,V> Comparator<Map.Entry<K,V>> comparingByKey(Comparator<? super K> cmp)

It returns the comparator that compares the objects by key using a given Comparator.

#static <K,V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue()

It returns the comparator that compare the objects in the natural order on value.

#static <K,V> Comparator<Map.Entry<K,V>> comparingByValue(Comparator<? super V> cmp)

It returns the comparator that compare the objects by value using the given Comparator.

#Java Map Example: comparingByKey()

See the following example of comparingByKey() method.

import java.util.*;

class JavaMap {
	public static void main(String args[]) {
		Map<Integer, String> map = new HashMap<Integer, String>();
		map.put(100, "Krunal");
		map.put(101, "Ankit");
		map.put(102, "Rushabh");
		map.entrySet()
			.stream()
			.sorted(Map.Entry.comparingByKey())
			.forEach(System.out::println);
	}
}

See the following output.

 

Java Map Example comparingByKey()

#Java Map Example: comparingByValue()

See the following code example.

import java.util.*;

class Jamap {
  public static void main(String args[]) {
    Map<Integer, String> map = new HashMap<Integer, String>();
    map.put(19, "Rushabh");
    map.put(20, "Ankit");
    map.put(21, "Krunal");
    map.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(System.out::println);
  }
}

See the following output.

 

Java Map Example comparingByValue()

#Using a HashMap Class

See the following code example.

import java.util.*;

class MapEx2{
	public static void main(String [] args){
		TreeMap<String, Integer> h = new TreeMap<String, Integer>();

		h.put("M", new Integer(0));
		h.put("A", new Integer(1));
		h.put("V", new Integer(2));
		h.put("E", new Integer(3));
		h.put("R", new Integer(4));
		h.put("I", new Integer(5));
		h.put("C", new Integer(6));
		h.put("K", new Integer(7));

		Set<Map.Entry<String, Integer>> set0 = h.entrySet();

		for(Map.Entry<String, Integer> a : set0){
			System.out.print(a.getKey() + ": ");
			System.out.println(a.getValue());
		}

		System.out.println();
	}
}

See the following code example.

 

Using a TreeMap Class

#Using a TreeMap Class

See the following code example.

import java.util.*;

class MapEx2{
	public static void main(String [] args){
		TreeMap<String, Integer> h = new TreeMap<String, Integer>();

		h.put("M", new Integer(0));
		h.put("A", new Integer(1));
		h.put("V", new Integer(2));
		h.put("E", new Integer(3));
		h.put("R", new Integer(4));
		h.put("I", new Integer(5));
		h.put("C", new Integer(6));
		h.put("K", new Integer(7));

		Set<Map.Entry<String, Integer>> set0 = h.entrySet();

		for(Map.Entry<String, Integer> a : set0){
			System.out.print(a.getKey() + ": ");
			System.out.println(a.getValue());
		}

		System.out.println();
	}
}

See the following example.

 

Using a HashMap Class

#Using a LinkedHashMap Class

See the following code example of LinkedHashMap.

import java.util.*;

class MapEx3{
	public static void main(String [] args){
		LinkedHashMap<String, Integer> h = new LinkedHashMap<String, Integer>();

		h.put("M", new Integer(0));
		h.put("A", new Integer(1));
		h.put("V", new Integer(2));
		h.put("E", new Integer(3));
		h.put("R", new Integer(4));
		h.put("I", new Integer(5));
		h.put("C", new Integer(6));
		h.put("K", new Integer(7));

		Set<Map.Entry<String, Integer>> set0 = h.entrySet();

		for(Map.Entry<String, Integer> a : set0){
			System.out.print(a.getKey() + ": ");
			System.out.println(a.getValue());
		}

		System.out.println();
	}
}

See the following output.

 

Using a LinkedHashMap Class

Finally, Java Map Interface Tutorial With Example | Map Interface in Java is over.

Leave A Reply

Your email address will not be published.

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