×

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 Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

Java Implements Keyword

To understand about the keyword implements we need to learn about the concept of the interfaces and inheritance in java programming languages. So let us learn about the interface and...

3 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

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

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.