TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Java HashMap Examples

This Java article uses the HashMap type from java.util.HashMap. This collection provides fast key lookups with hashing.

HashMap. Keys are often used, with computed hashes, to access values.

This is a lookup. Performance here is often critical. HashMap provides fast lookups.

This collection, available in java.util.HashMap, provides top performance and complete functionality. We call put() and get() to add and access elements.

Create. We create an example HashMap with keys of type String, values of Integer. On the right side of the declaration, the diamond inference feature is used.

Syntax: When we use a diamond, the left-side arguments are automatically chosen. This reduces syntax noise.

Based on:

Java 7

Java program that uses HashMap

import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

	// Create new HashMap.
	// ... Uses diamond inference on right side.
	HashMap<String, Integer> hash = new HashMap<>();

	// Put three keys with values.
	hash.put("dog", 1);
	hash.put("cat", 2);
	hash.put("rabbit", 3);

	// Look up some known values.
	int a = hash.get("dog");
	int b = hash.get("cat");

	// Display results.
	System.out.println(a);
	System.out.println(b);
    }
}

Output

1
2

Put, get. The put method receives two arguments. The first argument is the key we are trying to add to the HashMap. And the second is the value linked to that key.

Then: We call the get() method. This looks into the HashSet and, if found, returns the value for the key.

Caution: Please be careful not to call the get() method on a key that does not exist. An exception will be thrown.

Return: Please notice how the put() and get() methods receive and return the types specified in the HashMap declaration.

Keys. A HashMap often contains many keys. We can loop through these keys by first calling the keySet() method. We loop over the Set returned by keySet.

Tip: It is also possible to loop over the entries in the HashMap. This can eliminate the need for a value lookup in the for-loop.

For

Java program that loops over keys

import java.util.HashMap;
import java.util.Set;

public class Program {
    public static void main(String[] args) {

	// Create HashMap of three entries.
	HashMap<String, Integer> h = new HashMap<>();
	h.put("apple", 1);
	h.put("peach", 2);
	h.put("guava", 3);

	// Get keys.
	Set<String> keys = h.keySet();

	// Loop over String keys.
	for (String key : keys) {
	    System.out.println(key);
	}
    }
}

Output

guava
apple
peach

ContainsKey. Sometimes we need no value from the HashMap. Instead we just want to see if the key exists. We use the containsKey method for this purpose.

True: It returns true if the key is found, and false otherwise. We often test it in an if-statement.

If

Tip: The containsKey method is fast because a hash code is used to locate the key. Using containsValue() is slower—no hash is available.

Java program that uses containsKey

import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

	// Create an Integer HashMap.
	HashMap<Integer, Integer> h = new HashMap<>();
	h.put(1, 1000);
	h.put(20, 1001);
	h.put(300, 1003);

	// Use containsKey.
	if (h.containsKey(1)) {
	    System.out.println("1 was found");
	}
	if (h.containsKey(300)) {
	    System.out.println("300 was found");
	}
	if (!h.containsKey(400)) {
	    System.out.println("400 was not found");
	}
    }
}

Output

1 was found
300 was found
400 was not found

ContainsValue returns true if a specified value exists. Keys are not checked, just values. To get keys with a value, we must use a loop—more than one key may have a single value.

Java program that uses containsValue

import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

	// Create a HashMap of fruit and their color.
	HashMap<String, String> fruit = new HashMap<>();
	fruit.put("apple", "red");
	fruit.put("orange", "orange");
	fruit.put("banana", "yellow");
	fruit.put("raspberry", "red");

	// See if there is a red value.
	if (fruit.containsValue("red")) {
	    System.out.println("Red fruit detected!");

	    // Loop over all keys and print them if they have "red" values.
	    for (String key : fruit.keySet()) {
		if (fruit.get(key) == "red") {
		    System.out.println(key);
		}
	    }
	}
    }
}

Output

Red fruit detected!
raspberry
apple

Size. Every HashMap has a size. This is the count of entries (or of keys). For each key-value pair we add to HashMap, its size increases by one. The size() method returns this count.

Java program that uses size

import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

	// ... Create empty HashMap.
	HashMap<Integer, Integer> map = new HashMap<>();
	System.out.println(map.size());

	// ... Add one entry.
	map.put(1, 100);
	System.out.println(map.size());

	// Add two more entries.
	map.put(2, 200);
	map.put(3, 300);
	System.out.println(map.size());
    }
}

Output

0
1
3

IsEmpty. This returns true if the HashMap has a size of zero. It is the same thing as testing size() >0 but it may be easier to read. Testing for empty collections is a common requirement.

Boolean: This method returns a Boolean. It is often used within if-statements. But the Boolean can be used in any way.

Java program that uses isEmpty

import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

	HashMap<String, Boolean> map = new HashMap<>();

	// The HashMap is currently empty.
	if (map.isEmpty()) {
	    System.out.println("It is empty");
	}

	map.put("cat", true);
	map.put("dog", false);

	// IsEmpty now returns false.
	System.out.println(map.isEmpty());
    }
}

Output

It is empty
false

Values. We can get a collection of a HashMap's values with the values method. We must specify the type for values in the HashMap. Here we get String values.

Note: We then loop over the HashMap. We use a foreach-loop. Each element is of String type.

Java that uses values

import java.util.Collection;
import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

	HashMap<String, String> hash = new HashMap<>();
	hash.put("cat", "black");
	hash.put("dog", "brown");
	hash.put("bird", "blue");

	// Get all values from the HashMap.
	Collection<String> values = hash.values();
	for (String value : values) {
	    System.out.println(value);
	}
    }
}

Output

blue
black
brown

GetOrDefault. With this method, we safely get a value from our HashMap. If the key does not exist, no error occurs. Instead, the default value (argument 2) is returned.

Java that uses getOrDefault

import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

	// Create HashMap and put one key.
	HashMap<Integer, Integer> hash = new HashMap<>();
	hash.put(0, 10);

	// Get keys 0 and 1, returning -1 if nothing there.
	int result = hash.getOrDefault(0, -1); // Exists
	int result2 = hash.getOrDefault(1, -1); // Does not exist

	System.out.println(result);
	System.out.println(result2);
    }
}

Output

10
-1

PutIfAbsent. Put() will replace an existing value. But putIfAbsent() will not. It only adds the value to the HashMap if no key currently exists for it.

Tip: We can use putIfAbsent repeatedly if only the first encountered key needs to be retained.

Java that uses putIfAbsent

import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

	// Create HashMap and use putIfAbsent.
	HashMap<String, Double> hash = new HashMap<>();
	hash.putIfAbsent("cat", 1.5);
	hash.putIfAbsent("cat", 2.0);

	// ... This returns the first value added.
	double value = hash.get("cat");
	System.out.println(value);
    }
}

Output

1.5

Sort keys. A HashMap is unordered. It cannot be directly sorted, but we can sort its keys and process them (and their values) in order. We use keySet and add the keys to an ArrayList.

Collections.sort: We sort the ArrayList containing the keys with this method. The keys are now in ascending order.

Sort

Java that sorts HashMap

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;

public class Program {
    public static void main(String[] args) {

	HashMap<String, String> hash = new HashMap<>();
	hash.put("red", "color");
	hash.put("tomato", "fruit");
	hash.put("pizza", "lunch");

	// Put keys into an ArrayList and sort it.
	Set<String> set = hash.keySet();
	ArrayList<String> list = new ArrayList<String>();
	list.addAll(set);
	Collections.sort(list);

	// Display sorted keys and their values.
	for (String key : list) {
	    System.out.println(key + ": " + hash.get(key));
	}
    }
}

Output

pizza: lunch
red: color
tomato: fruit

Sort EntrySet, values. Sorting the values in a HashMap is somewhat complex. We access the EntrySet, which contains the key-value pairs in the HashMap.

Comparator: We implement a Comparator class called EntryComparator. In compare() it calls compareTo on the Entry's values.

ArrayList: In main, we copy the EntrySet to an ArrayList which can be sorted. We call addAll to add the Entries.

Sort: In ArrayList sort(), we pass our EntryComparer. This sorts the ArrayList of Entries by each Entry's value.

Java that sorts EntrySets

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map.Entry;

class EntryComparator implements Comparator<Entry<String, Integer>> {

    public int compare(Entry<String, Integer> arg0, Entry<String, Integer> arg1) {
	// Compare the values.
	return arg0.getValue().compareTo(arg1.getValue());
    }
}

public class Program {
    public static void main(String[] args) {

	// Create HashMap and add four pairs to it.
	HashMap<String, Integer> hash = new HashMap<>();
	hash.put("bird ", 500);
	hash.put("zebra", 2);
	hash.put("cat  ", 10);
	hash.put("dog  ", 5);

	// Copy keySet into ArrayList.
	// ... Sort with EntryComparator.
	ArrayList<Entry<String, Integer>> copy = new ArrayList<>();
	copy.addAll(hash.entrySet());
	copy.sort(new EntryComparator());

	// Display.
	for (Entry<String, Integer> e : copy) {
	    System.out.println(e.getKey() + "..." + e.getValue());
	}
    }
}

Output

zebra...2
dog  ...5
cat  ...10
bird ...500

HashMap versus ArrayList. In this benchmark, we search a HashMap for one key. We also search an ArrayList. Each collection has three keys. The HashMap delivers a stunning performance boost.

Result: The HashMap returns the correct result over two times faster than the ArrayList.

Tip: Even for small collection lookups, where only three elements exist, a HashMap locates an element faster. HashMap is a clear win.

Java that times HashMap, ArrayList

import java.util.HashMap;
import java.util.ArrayList;

public class Program {
    public static void main(String[] args) throws Exception {

	HashMap<Integer, Boolean> hash = new HashMap<>();
	hash.put(100, true);
	hash.put(1000, true);
	hash.put(50, true);

	ArrayList<Integer> array = new ArrayList<>();
	array.add(100);
	array.add(1000);
	array.add(50);

	long t1 = System.currentTimeMillis();

	// 1: Do HashMap lookups.
	for (int i = 0; i < 10000000; i++) {
	    if (!hash.containsKey(50)) {
		throw new Exception();
	    }
	}

	long t2 = System.currentTimeMillis();

	// 2: Do ArrayList lookups.
	for (int i = 0; i < 10000000; i++) {
	    if (!array.contains(50)) {
		throw new Exception();
	    }
	}

	long t3 = System.currentTimeMillis();

	// ... Times.
	System.out.println(t2 - t1);
	System.out.println(t3 - t2);
    }
}

Output

 91 ms,   HashMap:   containsKey
244 ms,   ArrayList: contains

Other collections. To sort a HashMap we can place its keys in an ArrayList, which we sort. With other collections, we can change how we view, and use data stored in a HashMap.

ArrayList

Hashtable. This collection does the same things as HashMap but is more thread-safe. Hashtable, for this reason, is slower and should usually be avoided.

Hashtable

TreeMap. This is a red-black binary tree. It provides fast access, insertion and removal. TreeMap implements many of the same methods found on HashMap.

TreeMap

EnumMap. We can place enums as keys within the HashMap. But Java provides an optimized EnumMap that looks up enum keys faster. It uses similar syntax.

EnumMap

HashSet. This is a HashMap with no values. In a HashSet we can invoke methods that are based on set theory. Sometimes we can replace a HashMap with a HashSet.

HashSet

Fast lookups are critical. If a collection with poor lookup performance is used, a program may, with large data sets, become unusable. With its hashing algorithm, HashMap is faster here.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf