×

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

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Composition in Java

Composition Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the...

3 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.

Java Sort String

In this article, you will be acknowledged about how to sort a string in Java. Introduction Firstly, let us revise what is string Strings are collections of characters that are frequently used in...

4 minutes read.

Gregorian Calendar Java Current Date

GregorianCalendar class uses the Gregorian and Julian calendars. Dates are calculated by projecting present laws forever backward and forward in time. As a consequence, GregorianCalendar may be utilised to create...

8 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

Java CountDownLatch

Another crucial classes for concurrent execution is CountDownLatch. It is a synchronisation tool that enables one or more threads to await until a series of tasks started by another thread...

4 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Sort Dates in Java

The Collection class's sort() method, which is a component of the Comparator mechanism, arranges the data in decreasing order. The Comparator interface can be used to accomplish the goal while...

4 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Static class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM is mostly...

7 minutes read.

Java Wrapper Class

Wrapper class in Java encapsulates a primitive type within an object. In other words, it is a unique mechanism of Java to convert primitive type in to object and object into primitive type....

3 minutes read.