Home » Java Basics » Java Map example

About Sotirios-Efstathios Maneas

Sotirios-Efstathios Maneas
Sotirios-Efstathios (Stathis) Maneas is a postgraduate student at the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. His main interests include distributed systems, web crawling, model checking, operating systems, programming languages and web applications.

Java Map example

In this example we will discuss about Maps in Java. A Map is an interface that maps keys to values. The keys are unique and thus, no duplicate keys are allowed. A map can provide three views, which allow the contents of the map to be viewed as a set of keys, collection of values, or set of key-value mappings. In addition, the order of the map is defined as the order in which, the elements of a map are returned during iteration.

The Map interface is implemented by different Java classes, such as HashMap, HashTable and TreeMap. Each class provides different functionality and can be either synchronized or not. Also, some implementations prohibit null keys and values, and some have restrictions on the types of their keys.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

Basic Methods

A map has the form Map <K, V> where:

  • K: specifies the type of keys maintained in this map.
  • V: defines the type of mapped values.

Furthermore, the Map interface provides a set of methods that must be implemented. In this section, we will discuss about the most famous methods:

  • clear: Removes all the elements from the map.
  • containsKey: Returns true if the map contains the requested key.
  • containsValue: Returns true if the map contains the requested value.
  • equals: Compares an Object with the map for equality.
  • get: Retrieve the value of the requested key.
  • keySet: Returns a Set that contains all keys of the map.
  • put: Adds the requested key-value pair in the map.
  • remove: Removes the requested key and its value from the map, if the key exists.
  • size: Returns the number of key-value pairs currently in the map.

Examples of Map

There are many classes that implement the Java Map interface. In this chapter, we will present the most common and used.

HashMap

The most common class that implements the Map interface is the Java HashMap. A HashMap is a hash table based implementation of the Map interface. It permits null keys and values. Also, this class does not maintain any order among its elements and especially, it does not guarantee that the order will remain constant over time. Finally, a HashMap contains two fundamental parameters: initial capacity and performance. The capacity is defined as the number of buckets in the hash table, while the load factor is a measure that indicates the maximum value the hash table can reach, before being automatically increased.

A simple example that uses a HashMap is shown below:

HashMapExample.java:

import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
	
	public static void main(String[] args) {
		Map vehicles = new HashMap();
		
		// Add some vehicles.
		vehicles.put("BMW", 5);
		vehicles.put("Mercedes", 3);
		vehicles.put("Audi", 4);
		vehicles.put("Ford", 10);
		
		System.out.println("Total vehicles: " + vehicles.size());
		
		// Iterate over all vehicles, using the keySet method.
		for(String key: vehicles.keySet())
			System.out.println(key + " - " + vehicles.get(key));
		System.out.println();
		
		String searchKey = "Audi";
		if(vehicles.containsKey(searchKey))
			System.out.println("Found total " + vehicles.get(searchKey) + " "
					+ searchKey + " cars!\n");
		
		// Clear all values.
		vehicles.clear();
		
		// Equals to zero.
		System.out.println("After clear operation, size: " + vehicles.size()); 
	}
}

A sample execution is shown below:

Total vehicles: 4
Audi - 4
Ford - 10
BMW - 5
Mercedes - 3

Found total 4 Audi cars!

After clear operation, size: 0

HashTable

The HashTable class implements a hash table and maps keys to values. However, neither the key nor the value can be null. This class contains two fundamental parameters: initial capacity and performance, with the same definitions as the HashMap class.

A simple example that uses a HashTable is shown below:

HashTableExample.java:

import java.util.Hashtable;
import java.util.Map;

public class HashTableExample {

	public static void main(String[] args) {
		Map vehicles = new Hashtable();
		
		// Add some vehicles.
		vehicles.put("BMW", 5);
		vehicles.put("Mercedes", 3);
		vehicles.put("Audi", 4);
		vehicles.put("Ford", 10);
		
		System.out.println("Total vehicles: " + vehicles.size());
		
		// Iterate over all vehicles, using the keySet method.
		for(String key: vehicles.keySet())
			System.out.println(key + " - " + vehicles.get(key));
		System.out.println();
		
		String searchKey = "Audi";
		if(vehicles.containsKey(searchKey))
			System.out.println("Found total " + vehicles.get(searchKey) + " "
					+ searchKey + " cars!\n");
		
		// Clear all values.
		vehicles.clear();
		
		// Equals to zero.
		System.out.println("After clear operation, size: " + vehicles.size());

		// The next statements throw a NullPointerException, if uncommented.
		//vehicles.put("Nissan", null);
		//vehicles.put(null, 6);
	}
}

A sample execution is shown below:

Total vehicles: 4
Audi - 4
Ford - 10
BMW - 5
Mercedes - 3

Found total 4 Audi cars!

After clear operation, size: 0

TreeMap

The TreeMap is a Red-Black tree implementation that is sorted according to the natural ordering of its keys, or by a Comparator provided at the creation time. Also, this class maintains an order on its elements. Finally, this class in not synchronized and thus, if an application uses multiple threads, the map must be synchronized externally.

A simple example that uses a TreeMap is shown below:

TreeMapExample.java:

import java.util.TreeMap;

public class TreeMapExample {

	public static void main(String[] args) {
		TreeMap vehicles = new TreeMap();
		
		// Add some vehicles.
		vehicles.put("BMW", 5);
		vehicles.put("Mercedes", 3);
		vehicles.put("Audi", 4);
		vehicles.put("Ford", 10);
		
		System.out.println("Total vehicles: " + vehicles.size());
		
		// Iterate over all vehicles, using the keySet method.
		for(String key: vehicles.keySet())
			System.out.println(key + " - " + vehicles.get(key));
		System.out.println();
		
		System.out.println("Highest key: " + vehicles.lastKey());
		System.out.println("Lowest key: " + vehicles.firstKey());
		
		System.out.println("\nPrinting all values:");
		for(Integer val: vehicles.values())
			System.out.println(val);
		System.out.println();
		
		// Clear all values.
		vehicles.clear();
		
		// Equals to zero.
		System.out.println("After clear operation, size: " + vehicles.size());
	}
}

A sample execution is shown below:

Total vehicles: 4
Audi - 4
BMW - 5
Ford - 10
Mercedes - 3

Highest key: Mercedes
Lowest key: Audi

Printing all values:
4
5
10
3

After clear operation, size: 0

As you can observe, the elements of the map are printed in a strict lexicographic order, which does not appear in the previous examples of HashMap and HashTable.

ConcurrentHashMap

The class is a hash table that supports full concurrency of retrievals. Thus, this structure is safe to use in case of multiple threads. Finally, this class does not allow neither keys nor values to be null.

A simple example that uses a ConcurrentHashMap is shown below:

ConcurrentHashMapExample.java:

import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapExample {
	
	public static void main(String[] args) {
		ConcurrentHashMap vehicles = new ConcurrentHashMap();
		
		// Add some vehicles.
		vehicles.put("BMW", 5);
		vehicles.put("Mercedes", 3);
		vehicles.put("Audi", 4);
		vehicles.put("Ford", 10);
		
		System.out.println("Total vehicles: " + vehicles.size());
		
		// Iterate over all vehicles, using the keySet method.
		for(String key: vehicles.keySet())
			System.out.println(key + " - " + vehicles.get(key));
		System.out.println();
		
		String searchKey = "Audi";
		if(vehicles.containsKey(searchKey))
			System.out.println("Found total " + vehicles.get(searchKey) + " "
					+ searchKey + " cars!\n");
		
		Enumeration elems = vehicles.elements();
		while(elems.hasMoreElements())
			System.out.println(elems.nextElement());
		System.out.println();
		
		Integer val = vehicles.putIfAbsent("Audi", 9);
		if(val != null)
			System.out.println("Audi was found in the map and its value was updated!");
		
		val = vehicles.putIfAbsent("Nissan", 9);
		if(val == null)
			System.out.println("Nissan wasn't found in map, thus a new pair was created!");
		System.out.println();
		
		// The next statements throw a NullPointerException, if uncommented.
		//vehicles.put("Nissan", null);
		//vehicles.put(null, 6);
		
		// Clear all values.
		vehicles.clear();
		
		// Equals to zero.
		System.out.println("After clear operation, size: " + vehicles.size());
	}
}

A sample execution is shown below:

Total vehicles: 4
BMW - 5
Mercedes - 3
Audi - 4
Ford - 10

Found total 4 Audi cars!

5
3
4
10

Audi was found in the map and its value was updated!
Nissan wasn't found in map, thus a new pair was created!

After clear operation, size: 0

Download The Eclipse Project

The Eclipse project of this example: MapExample.zip

 
This was a tutorial about Maps in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.