Java Map [With Examples]

Introduction

The Java map interface is present in java.util package represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit differently from the rest of the collection types. A map contains unique keys.

Maps, such as dictionaries, are ideal for key-value association mapping. The maps are use to do key lookups or to obtain and update items based on keys. Here are some examples of such scenarios:

  • A map of error codes and their descriptions.
  • Map of zip codes and cities.
  • A map of managers and employees. Each manager (key) is associate with a list of employees (value) he manages.
  • A map of classes and students. Each class (key) is associate with a list of students (value).
map interface

Creating Java Map Objects

Because Map is an interface, objects of the type map cannot be create. To build an object, we always require a class that extends this map. Furthermore, since the advent of Generics in Java 1.5, the kind of object that may be store in the Map can be restrict.

Syntax:

Map hm = new HashMap(); 

Characteristics of Java Map Interface

  1. A Map cannot have multiple keys, and each key can only map to one value. Some implementations, such as HashMap and LinkedHashMap, support null keys and values, whereas others, such as TreeMap, do not.
  2. The order of a map is determine by the implementation. TreeMap and LinkedHashMap, for example, have predictable ordering, but HashMap does not.
  3. In Java, there are two interfaces for implementing Map. There are two types: Map and SortedMap, as well as three classes: HashMap, TreeMap, and LinkedHashMap.

Methods in Java Map Interface

MethodDescription
clear()This method clears and removes all items or mappings from a given Map collection.
containsKey(Object)Method is used to determine whether or not a specific key is mapped into the Map. It accepts as an input the key element and returns True if that element is mapped in the map.
containsValue(Object)This method determines whether a certain value in the Map is mapped by a single or many keys. It accepts the value as an argument and returns True if any of the keys in the map map to that value.
entrySet()Method is use to construct a set using the same components seen in the map. It basically returns a set view of the map, but we can also construct a new set and store the map items in it.
equals(Object)This method is used to compare the equality of two maps. It checks if the elements of one map supplied as a parameter are the same as the elements of this map.
get(Object)Method is used to obtain or fetch the value associated with a certain key specified in the argument. When there is no such mapping for the key in the map, it returns NULL.
hashCode()This method generates a hashCode from the provided map of keys and values.
isEmpty()Method is used to determine if a map contains any entries for key and value pairs. If there is no mapping, this returns true.
keySet()This method is used to return a Set representation of the keys in this map. Because the set is supported by the map, changes to the map are mirrored in the set and vice versa.
put(Object, Object)In this map, this method is used to associate the supplied value with the specified key.
putAll(Map)This method copies all mappings from the supplied map to this map.
remove(Object)If the mapping for a key is existing in the map, this technique is used to delete it.
size()This function returns the number of key/value pairs that are accessible in the map.
values()Method is used to generate a collection from the map’s values. It basically returns a Collection view of the HashMap’s values.
getOrDefault(Object key, V defaultValue)Returns the value to which the specified key is mapped, or defaultValue if no mapping for the key exists in this map.
merge(K key, V value, BiFunction remappingFunction)Associates the specified key with the provided non-null value if it is not already associated with a value or is associated with null.
putIfAbsent(K key, V value)If the specified key has not previously been linked with a value (or is mapped to null), it associates it with the given value and returns null; otherwise, it returns the current value.

Java Map Interface Example

Code 01: Below snippet will shows you Traversing through java map foreach example

// Java Program to Demonstrate
// Working of Map interface

// Importing required classes
import java.util.*;

// Main class
class Main {

	// Main driver method
	public static void main(String args[])
	{
		// Creating an empty HashMap
		Map<String, Integer> hashmap= new HashMap<String, Integer>();

		// Inserting pairs in above Map
		// using put() method
		hashmap.put("Banana", new Integer(100));
		hashmap.put("Orange", new Integer(200));
		hashmap.put("Mango", new Integer(300));
		hashmap.put("Apple", new Integer(400));

		// Traversing through Map using for-each loop
		for (Map.Entry<String, Integer> map :
			hashmap.entrySet()) {

			// Printing keys
			System.out.print(map.getKey() + ":");
			System.out.println(map.getValue());
		}
	}
}

Output:

Apple:400
Mango:300
Orange:200
Banana:100

Classes that implement Map

We cannot create objects from Map because it is an interface. These classes can be use to access Map interface functionality.

The Map interface is also extend by these subinterfaces:

  • SortedMap
  • NavigableMap
  • ConcurrentMap

Implementation of Map Interface Calsses

Class 01: Implementation of HashMap Class

HashMap has been a part of the Java collection since Java 1.2. It implements the Java Map interface in its most basic form. It keeps data in (Key, Value) pairs. To access a value, the key must be known. This class employs the Hashing method. Hashing is a method of reducing a huge String to a little String that represents the same String. A shorter value aids in indexing and searches.

Code 02:

// Java Program to illustrate the Hashmap Class

// Importing required classes
import java.util.*;

// Main class
public class Main {

	// Main driver method
	public static void main(String[] args)
	{

		// Creating an empty HashMap
		Map<String, Integer> hashmap = new HashMap<>();

		// Inserting entries in the Map
		// using put() method
		hashmap.put("Banana", 100);
		hashmap.put("Orange", 200);
		hashmap.put("Mango", 300);
		hashmap.put("Apple", 400);

		// Iterating over Map
		for (Map.Entry<String, Integer> e : hashmap.entrySet())

			// Printing key-value pairs
			System.out.println(e.getKey() + " "+ e.getValue());
	}
}

Output:

Apple 400
Mango 300
Orange 200
Banana 100

Class 02: Implementation of LinkedHashMap Class

LinkedHashMap is similar to HashMap, except it also maintains the order of elements added into it. HashMap has the benefit of speedy insertion, search, and deletion, but it never kept track of the track and order of insertion that LinkedHashMap has, where the components may be retrieve in their insertion order.

Code 03:

// Java Program to Illustrate the LinkedHashmap Class

// Importing required classes
import java.util.*;

// Main class
public class Main {

	// Main driver method
	public static void main(String[] args)
	{

		// Creating an empty LinkedHashMap
		Map<String, Integer> hashmap = new LinkedHashMap<>();

		// Inserting entries in the Map
		// using put() method
		hashmap.put("Banana", 100);
		hashmap.put("Orange", 200);
		hashmap.put("Mango", 300);
		hashmap.put("Apple", 400);

		// Iterating over Map
		for (Map.Entry<String, Integer> e : hashmap.entrySet())

			// Printing key-value pairs
			System.out.println(e.getKey() + " "+ e.getValue());
	}
}

Output:

Banana 100
Orange 200
Mango 300
Apple 400

Class 03: Implementation of TreeMap Class

In Java, the TreeMap is use to implement the Map interface, as well as the NavigableMap and the Abstract Class. Depending on whether function Object() { [native code] } is used, the map is sorted according to the natural ordering of its keys or by a Comparator specified at map formation time. This is an effective method of sorting and storing key-value pairs. The storage order maintained by the treemap, like any other sorted map, must be consistent with equals, regardless of the specified comparators.

Code 04:

// Java Program to Illustrate TreeMap Class

// Importing required classes
import java.util.*;

// Main class
public class Main {

	// Main driver method
	public static void main(String[] args)
	{

		// Creating an empty TreeMap
		Map<String, Integer> hashmap = new TreeMap<>();

		// Inserting entries in the Map
		// using put() method
		hashmap.put("Banana", 100);
		hashmap.put("Orange", 200);
		hashmap.put("Mango", 300);
		hashmap.put("Apple", 400);
		
		// Iterating over Map using for each loop
		for (Map.Entry<String, Integer> e : hashmap.entrySet())

			// Printing key-value pairs
			System.out.println(e.getKey() + " "+ e.getValue());
	}
}

Output:

Apple 400
Banana 100
Mango 300
Orange 200

Basic Operations of Java Map Interface

The Java Map interface contains a number of methods for performing various operations on hashmaps using hashmap class.

  1. Add elements
  2. Change or Replace elements
  3. Remove elements

Operation 01: Add Elements

Code 05:

// Java program to demonstrate
// the working of Map interface

import java.util.*;
class Main {
	public static void main(String args[])
	{
		// Default Initialization of a
		// Map
		Map<Integer, String> hashmap1 = new HashMap<>();

		// Initialization of a Map
		// using Generics
		Map<Integer, String> hashmap2= new HashMap<Integer, String>();

		// Inserting the Elements
		hashmap1.put(1, "Apple");
		hashmap1.put(2, "Banana");
		hashmap1.put(3, "Mango");

		hashmap2.put(new Integer(1), "Mango");
		hashmap2.put(new Integer(2), "Apple");
		hashmap2.put(new Integer(3), "Banana");

		System.out.println(hashmap1 +"\n");
		System.out.println(hashmap2);
	}
}

Output:

{1=Apple, 2=Banana, 3=Mango}

{1=Mango, 2=Apple, 3=Banana}

Operation 2: Changing Elements

Code 06:

// Java program to demonstrate
// the working of Map interface

import java.util.*;
class Main {
	public static void main(String args[])
	{

		// Initialization of a Map
		// using Generics
		Map<Integer, String> hashmap1= new HashMap<Integer, String>();

		// Inserting the Elements
		hashmap1.put(1, "Apple");
		hashmap1.put(2, "Banana");
		hashmap1.put(3, "Mango");

		System.out.println("Initial Map " + hashmap1+"\n");

		hashmap1.put(new Integer(2), "Orange");

		System.out.println("Updated Map " + hashmap1);
	}
}

Output:

Initial Map {1=Apple, 2=Banana, 3=Mango}
Updated Map {1=Apple, 2=Orange, 3=Mango}

Operation 03: Removing Elements

Code 07:

// Java program to demonstrate
// the working of Map interface

import java.util.*;
class Main {

	public static void main(String args[])
	{

		// Initialization of a Map
		// using Generics
		Map<Integer, String> hashmap1= new HashMap<Integer, String>();
		
		// Inserting the Elements
		hashmap1.put(1, "Apple");
		hashmap1.put(2, "Banana");
		hashmap1.put(3, "Mango");

		// Initial Map
		System.out.println("Initial Map :"+hashmap1+"\n");

		hashmap1.remove(new Integer(2));

		// Final Map
		System.out.println("Updated Map :"+hashmap1);
	}
}

Output:

Initial Map :{1=Apple, 2=Banana, 3=Mango}

Updated Map :{1=Apple, 3=Mango}

Iterating Through the Java Map

There are several methods for iterating through the Map. The most well-known method is to utilise a for-each loop to get the keys. The getValue() function is used to determine the value of the key.

Code 08:

// Java program to demonstrate
// the working of Map interface

import java.util.*;
class Main {
	public static void main(String args[])
	{

		// Initialization of a Map
		// using Generics
		Map<Integer, String> hashmap1= new HashMap<Integer, String>();

		// Inserting the Elements
		hashmap1.put(1, "Apple");
		hashmap1.put(2, "Banana");
		hashmap1.put(3, "Mango");


		for (Map.Entry mapElement : hashmap1.entrySet()) {
			int key= (int)mapElement.getKey();

			// Finding the value
			String value= (String)mapElement.getValue();
			System.out.println(key + " : "+ value);
		}
	}
}

Output:

1 : Apple
2 : Banana
3 : Mango

Conclusion

That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. Java Hashmap [With Examples]
  2. What is Treemap in Java?

Leave a Comment