Sotirios-Efstathios Maneas

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

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.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books