×

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

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.

Java Thread class

Thread class The thread represents a part of the process. Every process can have multiple associated threads in which every thread may execute the same or different job. By default, each thread assigns...

16 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

Objects and Classes in Java

Objects and Classes in Java Classes and objects are the basic concepts of object-oriented programming. It revolves around the real world entity. In Java, the object is a physical and logical...

5 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Order of Execution of Constructors in Java Inheritance

Constructor in Java There are several distinctions between a method and a function object() in Java. The name of the function object()  is identical to the class name. There is no...

4 minutes read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 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.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Arrow Operator in Java

The introduction of arrow functions in ES6 gives you a more precise approach to define JavaScript functions. We can write shorter function syntax thanks to them. Your code will be...

4 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.