×

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs.

  • HashMap: HashMap stores the keys in a hash table. It uses the hashCode() method of the keys to retrieve their value efficiently. The benefit is that the storing and retrieving of the values by key have constant time. The disadvantage is that we lose the order of the insertion.
  • TreeMap: TreeMap stores the key in a sorted tree structure. The benefit is that the key is always in sorted order but adding and checking of elements by the key takes longer time O(log n).
  • Hashtable: Hashtable is an array of the list. Each list is known as a bucket. The position of the bucket is identified by calling the hashcode() method. A Hashtable contains values based on the key. It contains only unique elements. It does not allow null key or value. It is synchronized.

Useful Methods

Modifier and Type

Method

Description

void

clear()

It removes all keys and values from the map.

boolean

isEmpty()

It returns whether the map is empty.

int

size()

It returns the number of entries (key/value pairs) in the map.

V

get(Object key)

It returns the value mapped by key or null if none is mapped.

V

put(K key, V value)

It adds or replaces key/value pair. Returns previous value or null.

V

remove(Object key)

It removes and returns the value mapped to the key. Returns null if none.

boolean

containsKey(Object key)

It returns whether the key is in the map.

boolean

containsValue(Object)

It returns value is in map.

Set<K>

keySet()

It returns set of all keys.

Collection<V>

values()

It returns Collection of all values.

Example

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class MapExample {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("key1", "INDIA");
map.put("key2", "CHINA");
map.put("Key3", "NEPAL");
String s = map.get("Key1"); // INDIA
for (Entry<String, String> key : map.entrySet())
System.out.print(key.getValue() + ","); // INDIA,CHINA,NEPAL,
}
}

output:

INDIA,CHINA,NEPAL,

Example: TreeMap

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MyClass {
public static void main(String args[]) {
/* This is how to declare TreeMap */
TreeMap<String, Integer> treemap = new TreeMap<>();
/* Adding elements to TreeMap */
treemap.put("A", 1);
treemap.put("C", 3);
treemap.put("B", 2);
treemap.put("E", 5);
treemap.put("D", 4);
/* Display content using Iterator */
Set set = treemap.entrySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry mapentry = (Map.Entry) iterator.next();
System.out.print("key is: " + mapentry.getKey() + " & Value is: ");
System.out.println(mapentry.getValue());
}
}
}

Output:

key is: A & Value is: 1
key is: B & Value is: 2
key is: C & Value is: 3
key is: D & Value is: 4
key is: E & Value is: 5

Example: HashTable

import java.util.Hashtable;
import java.util.Map.Entry;
import java.util.Set;

public class MyClass {
public static void main(String[] arg)
{
// creating a hash table
Hashtable<String,Integer> hashTable = new Hashtable<>();
hashTable.put("A", 1);
hashTable.put("C", 3);
hashTable.put("B", 2);
hashTable.put("E", 5);
hashTable.put("D", 4);
// checking whether hash table h is empty or not
if (hashTable.isEmpty())
System.out.println("yes hash table is empty");
// creating set view for hash table
Set<Entry<String,Integer>> s = hashTable.entrySet();
// printing set entries
System.out.println("set entries: " + s);
// obtaining hash code
System.out.println("hash code is: " + hashTable.hashCode());
// remove value for 2 from Hashtable h
hashTable.remove("C");
// checking Hashtable h
System.out.println("values after remove: " + hashTable);
}
}

Output:

set entries: [A=1, E=5, D=4, C=3, B=2]
hash code is: 320
values after remove: {A=1, E=5, D=4, B=2}

Related Topics

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

ArrayDeque in Java

ArrayDeque The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This...

8 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

6 minutes read.

Java Math floor() Method

The floor() method of Math class returns the largest double value that is equal to a mathematical integer and is less than or equal to the argument. Syntax: public static double floor(double...

2 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

Isomorphic String in Java

In this tutorial, we will understand what is meant by isomorphic String in java. We will also see a Java program to find out if the string is isomorphic or...

4 minutes read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.