×

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

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

3N+1 problem program in Java

The 3N+1 problem is a hypothesis in the field of abstract mathematics (not yet proven). Collectively known as the Collatz problem. This tutorial will describe about the 3N+1 problem and...

3 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

Math fma () method in java

In java, the Math module constitutes of fma () Method in it. This method can be accessed in two ways which can be differentiated by the parameters which are given...

4 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

Java Integer reverse() method

The reverse() method of Java Integer class returns the value obtained by reversing the order of the bits in the 2’s complement binary representation. Syntax public static int reverse (int i)  Parameters The parameter...

1 minute read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

Thread Program in Java

Thread Program in Java Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading,...

8 minutes read.