×

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

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

How to Calculate Time Difference Between Two Dates in Java?

Date is being used extensively in Java to calculate date differences. While constructing an application, the date of joining an organisation, admission date, appointment date, and others might be included....

4 minutes read.

Java Garbage Collection

Java Garbage Collection In Java, unreferenced objects are treated like garbage. The process of reclaiming the unused memory during runtime automatically is known as the Java Garbage Collection.In other words, the...

4 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Cyclic Barrier in Java

Programmers often find it challenging to run multiple threads simultaneously. Java introduces the idea of concurrency, which enables us to run many threads concurrently, making this work simpler. Concurrent programming...

6 minutes read.

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

Dictionary in Java

Dictionary in Java The Dictionary class represents a key-value relation which maps keys to values. In Dictionary class, every key and every value is an object. It is an abstract class associated with...

2 minutes read.

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.