×

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.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

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

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Factorial of a Large Number in Java

We've already talked about a number's factorial. We must still go over the factorial of a large number separately, though. The method used to determine the factorial of a small...

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

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

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 tan() Method

The tan() method of Java Math class returns the trigonometric tangent of the specified angle. Syntax: public static double tan(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The tan() method...

2 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

Java Boolean equals() method

The equals() method of Java Boolean class returns a Boolean value true if the specified argument is not null and is same as this object, else it returns false. Syntax public boolean...

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

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

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