Map in Java: All about Map Interface in Java

  • Written By  

  • Published on December 3rd, 2022

Table of Contents [show]

 

Introduction

 

A map is an object that contains values based on a key (a key and value pair that are known as an "entry"). Each key can map to at most one value and contains no duplicate keys but unique keys in a map. It models the mathematical operation "abstraction." A map is reasonable if you have to explore, update, or delete elements based on a key.

 

 

Map Interface in Java

 

The Java Map interface is a set of frameworks that produce map data structure processing. The Map interface supports three distinct sets: the set of keys, the set of values, and the set of key/value associations (mapping). The map interface is carried in the "java.util" package and defines a mapping between a key and a value. Since the Collection interface doesn't contain the Map interface as a subtype, it acts differently from other collection types.

 

 

Working on Map Interface in Java

 

The mapping of keys to values, where the key is unique and is an entity to retrieve the value at the latest date, is done by the Java Map interface. Now, the key gives the value stored in a Map object. After storing the value, you can recover it by operating its key. Several methods throw NoSuchElementException when no objects are present in the invoking map. Then ClassCastException is thrown for the object that is incompatible with the elements in a map. A NullPointerException is an attempt to use a null object & null is not allowed in the map. UnsupportedOperationException when an attempt is made to change an unmodifiable map.

 

 

Our Learners Also Read: What are the Characteristics of Java?

 

 

Methods of Map in Java

 

Entry is the subinterface of the Java Map interface. So we'll use a map to get their entry name which produces a collection view of the map, whose details are of this class. It delivers forms to obtain the key and value. The Map interface in Java includes the following methods:

 

  • "put"(K, V) – It aims to insert the connection of a key K and a value V into the map. New value replaces the old value if the key is already present.
  • putAll() – It aims to insert all the entries from the selected map into the new map.
  • putIfAbsent(K, V) – It aims to insert the affinity if the key K is not associated with the value V.
  • "get"(K) – It aims to replace the value associated with the specified key K. It returns invalid if the key not discovered.
  • getOrDefault(K, defaultValue) – It aims to return the value associated with the specified key K. It produces the defaultValue, if the key not seen.
  • containsKey(K) – It determines if the specified key K is present in the map.
  • containsValue(V) – It determines if the specified value V is present in the map.
  • "replace"(K, V) – It aims to replace the new specified value V with the value of the key K.
  • "replace"(K, oldValue, newValue) – If the key K is associated with the value oldValue, it aims to replace the value of the key K with the new value newValue.
  • "remove"(K) – If the key K is associated with the value oldValue, it aims to replace the value of the key K with the new value newValue.
  • "remove"(K, V) – It remove the entry from the map key K associated with value V.
  • keySet() – It aims to return a set of all the keys in a map.
  • "values"() – It aims to return a set of all the values in a map.
  • entrySet() – It aims to return a set of all the key/value mapping present in a map.

 

 

 

Types of Map Interface in Java

 

There are three classes of map interface in Java: HashMap, LinkedHashMap, and TreeMap. TreeMap does not support null keys or values, whereas HashMap and LinkedHashMap do. 

 

 

HashMap: It is the performance of the map, but it doesn't carry any demand. HashMap is a class to execute processes such as inserting, deleting, and locating elements in a map. We should avoid using hash maps when it is significant to keep the exact order of objects in a group.

 

"Syntax- public class HashMap extends AbstractMap implements Map "

 

 

LinkedMap: The execution of the map as it inherits the HashMap class and preserves insertion order. The Java Collections Framework's LinkedHashMap class implements the map interface's hash table and linked list. 

 

"Syntax- public class LinkedHashMap extends HashMap implements Map "

 

 

TreeMap: The implementation of map and SortedMap maintains ascending order. It delivers an efficient tool for keeping key-value pairs in the sorted hierarchy.

 

"Syntax- public class TreeMap extends AbstractMap implements NavigableMap "

 

Convert List to Map in Java

 

The collection's child interface is the List. It is a requested set of objects in which duplicate values are stored. Since it maintains the insertion declaration, it permits positional access and insertion of elements. ArrayList, LinkedList, Vector, and Stack classes implement the List Interface. 

Here is the program to convert List to Map using Java

 

“// Java program for list convert in map

// with the help of Object method

 

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import java.util.HashMap;

 

// create a list

class Student {

 

// id will act as Key

private Integer id;

 

// name will act as value

private String name;

 

// create curstuctor for reference

public Student(Integer id, String name)

{

 

// assign the value of id and name

this.id = id;

this.name = name;

}

 

// return private variable id

public Integer getId()

{

return id;

}

 

// return private variable name

public String getName()

{

return name;

}

}

 

// main class and method

public class GFG {

 

// main Driver

public static void main(String[] args)

{

 

// create a list

List

lt = new ArrayList();

 

// add the member of list

lt.add(new Student(1, "Map"));

lt.add(new Student(2, "in"));

lt.add(new Student(3, "Java"));

 

// create map with the help of

// Object (stu) method

// create object of Map class

Map map = new HashMap<>();

 

// put every value list to Map

for (Student stu : lt) {

map.put(stu.getId(), stu.getName());

}

 

// print map

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

}

}”

Output: 

Map  : {1=Map, 2=in, 3=Java}”

 

Map.Entry Interface using Java

 

In Java, the Map.Entry interface provides various methods for accessing a map entry. By acquiring access to the map's entries we can efficiently manage them. "Map.Entry" is a generic class described in the "java.util" package. 

The program below illustrates the working of Map.Entry

 

“// Java Program to demonstrate the

// methods of Map.Entry

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.Set;

 

public class GFG

{

public static void main(String[] args)

{

// Create a LinkedHashMap

LinkedHashMap m =

new LinkedHashMap();

 

m.put("1 – Bedroom" , 25000);

m.put("2 – Bedroom" , 50000);

m.put("3 – Bedroom" , 75000);

m.put("1 – Bedroom – hall", 65000);

m.put("2 – Bedroom – hall", 85000);

m.put("3 – Bedroom – hall", 105000);

 

// Using entrySet() to get the entry's of the map

Set> s = m.entrySet();

 

for (Map.Entry it: s)

{

// Using the getKey to get key of the it element

// Using the getValue to get value of the it element

System.out.println("Before change of value = " +

it.getKey() + " " + it.getValue());

 

// Changing the value of 1 – Bedroom.

double getRandom = Math.random() * 100000;

int getRoundoff = (int) Math.round(getRandom);

 

// Using setValue to change the value of the

// map element

it.setValue(getRoundoff);

 

System.out.println("After change of value = " +

it.getKey() + " " + it.getValue());

}

}

}”

 

Output:

 

“Before change of value = 1 – Bedroom   25000

After change of value = 1 – Bedroom   59475

Before change of value = 2 – Bedroom   50000

About The Author:

logo

Digital Marketing Course

₹ 29,499/-Included 18% GST

Buy Course
  • Overview of Digital Marketing
  • SEO Basic Concepts
  • SMM and PPC Basics
  • Content and Email Marketing
  • Website Design
  • Free Certification

₹ 41,299/-Included 18% GST

Buy Course
  • Fundamentals of Digital Marketing
  • Core SEO, SMM, and SMO
  • Google Ads and Meta Ads
  • ORM & Content Marketing
  • 3 Month Internship
  • Free Certification
Trusted By
client icon trust pilot
1whatsapp