×

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework is to provide the functionality of Map in the data structures.

Java map does not allow duplicated keys. It will enable only the unique keys, but it can take duplicated values. So here, the value pairs and the keys are called an entry.

The map interface is available in java. util a package that maps between the key and the value.

A map of students and subjects. Each subject(key) relates to the set of Students(value).

A map of workers and owners. Each owner(key) relates to the worker's (value) set.

For example:

                        Key             Value

                        Red---------apple

                        Yellow-----banana

                        White------radish

The delete, search, and update operations are done using the keys.

Mainly there are three classes for the mapping Linked HashMap, Treemap, and HashMap.

For the implementation of Map, there are two interfaces: Map and Sorted Map.

Linked HashMap: Linked HashMap inherits the HashMap and is used for the maintenance of insertion and the implementation of Map.

TreeMap: TreeMap maintains the ascending order and is used to implement Map and Sorted Map.

HashMap: Hash map does not maintain any order and is used to implement Map.

In java, objects cannot be created in the type of Map, so we need a class that extends the Map for creating an object.

Syntax:  Map ht=new HashMap ();

Map <Key, Value> contacts=new HashMap<>();//for HashMap

Methods in Map Interface:

1.put (obj k, obj Val):

This method is used for inserting an entry into the Map.

2.putlfAbsent (K key, V value):

It is used for inserting specified Map in the Map.

3.remove (obj k):

This method deletes an entry in the Map for a specified key.

4. Set< Map. Entry<Key, Value>> entry Set ():

It is the set of keys and value pairs.

5.void clear ():

It is used to reset and clear the Map.

6.contains key(obj):

This method tells us whether the key got mapped or not. It takes a key element as a parameter and returns true when it got mapped; otherwise returns false.

7.contains value(obj):

This method tells us whether the value got mapped or not and by a single or more than one key.

8.get(obj):

This method is mainly used to retrieve the value mapped by the key.

9.size ():

It returns the number of keys or values available on the Map.

10.putAll ():

Entries are inserted from the specified Map to this Map.

11.replace (key, value):

This method is used to replace the value of a key with a particular or specified value

12.remove(key):

This method removes the entry from the Map represented by the key.

13.remove (key, value):

It removes the key associated with the value entry of the Map.

14.keySet ():

It returns all the sets of keys present on the Map.

15.values ():

It is used to return all the values present on the Map.

16.entrySet ():

It returns a set of all keys or values mappings on the Map.     

Java Map Example code (NON-GENRIC) Old Style:

import java.io. *;
import java.util.*;
public class Map1
{
public static void main (String [] args)
{
Map ht=new HashMap ();
ht.put (1," Ramu");
ht.put (2," Mani");
ht.put (3," Teja");
ht.put (4," Abi");
Set st=ht. entrySet ();
Iterator it=st. iterator ();
while (it. hasNext ())
{
Map.Entry entry= (Map.Entry) it.next();
System.out.println(entry. getKey () +" "+entry. getValue ());
}
}
}

Output:

Java Map Example

Java Map Example code (GENRIC) New Style:

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


Map<Integer, String> ht=new HashMap<Integer, String>();  
ht.put (1," Ramu");
ht.put (2," Mani");
ht.put (3," Teja");
ht.put (4," Abi");
for (Map.Entry m:ht.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

Output:

Java Map Example

Operations performed on Map

1. Addition of Elements

To add an element to the Map, we use the put () method, but HashMap does not confirm the insertion order, .so the facets are indexed based on the hash to make them more efficient internally.

2. Changing the Elements

The keys index the elements in the Map, and the values can be changed by updating or inserting a matter of a key we require to change.

3. Removal of elements

To remove an element from the entry, we use the remove() method, which will remove the mapping of a key that is associated with that value in the Map of an entry.


Related Topics

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Longest Arithmetic Progression Sequence in Java

The task is to find the length of the largest sequence in an array to form an arithmetic progression. The array arr[] is given. Longest Arithmetic Progression Sequence in Java Algorithm set...

5 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

How to Set Java_home in Linux

To set the Java_home in Linux, we must follow several steps to make us understand it easily.  Java follows the principle called WORA (write once run anywhere). We know that java...

3 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Accessors and Mutator in Java

Introduction Accessors and mutators are used in Java to get and set the value of private fields, respectively. Accessors and mutators are both referred to as getters and setters, respectively. The...

6 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

How to add 4 Hours to the Current Date in Java?

In this tutorial, we will learn how to add 4 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the...

4 minutes read.

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.