In the earlier tutorials, the focal point had been Java Basics and OOPs concepts. In this tutorial, we are going to learn about one of the core concepts of Java Collections, i.e., Java HashMap with the help of examples.
Before we dive into what is a hashmap and what are its key functions, let us first know what Collections in Java are.
Table of Contents
Collections represent a single unit of objects, i.e. a group. It is basically a framework that provides the base to store and manipulate the group of objects.
The Java collection framework provides us with many interfaces and classes to correspond to a group of objects as a single unit.
HashMap is a Map-based class in Java Collections. It implements the Map interface and extends the features of the AbstractMap abstract class.
HashMap is referred to as a collection class that stores items in the form of key and value pairs. It is denoted as
HashMap<Key, Value> or HasMap<K,V>
Properties of HashMap:
How to use HashMap in Java?
In order to use HashMap class and its methods, one needs to import java.util.HashMap
or its superclass.
What is the difference between HashMap and HashTable?
HashMap follows the basic concepts of hashtable with the exception of accepting null values and is unsynchronized.
Following is a basic example of HashMap, where in we will be creating a HashMap called birdsMap that will store Integer keys and String values.
In this program, we will also have a sneak peek into the various ways of iterating a HashMap.
Programming example covers:
In this code, we are using different flow control statements to iterate over entries in the HashMap.
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
public class HashMapExample {
public static void main(String []args) {
//A HashMap object called birds.
HashMap<Integer, String> birdsMap = new HashMap<Integer, String>();
//Add key and value pairs to birds (Integer, BirdName)
birds.put(1, "Parrot");
birds.put(2, "Falcon");
birds.put(3, "Swans");
birds.put(4, "Woodpecker");
birds.put(5, "Owl");
//Printing the entrySet with the help of for-each loop.
System.out.println("====Using for-each loop====");
for(Map.Entry<Integer,String> entry : birdsMap.entrySet()) {
System.out.println("Key:= " + entry.getKey " , Value:= " + getValue());
}
//Printing the key-value pairs using Iterator.
System.out.println("====Using Iterator====");
Iterator<Map.Entry<Integer, String>> itr = birdsMap.entrySet().iterator();
while(itr.hasNext()) {
Map.Entry<Integer, String> entry = itr.next();
System.out.println("Key:= " + entry.getKey " , Value:= " + getValue());
}
//Printing the key-value pair using forEach method of Java 8.
System.out.println("====Using forEach method of Java 8====");
birdsMap.forEach((k,v) -> System.out.println("Key:=" +k + " , Value=>" + v));
//Iterating just over keys.
System.out.println("====Iterating over just keys====");
for(Integer key : birdsMap.keySet()) {
System.out.println("Key:=" +key);
}
//Iterating just over values.
System.out.println("====Iterating over just values====");
for(String value : birdsMap.values()) {
System.out.println("Value:=" +value);
}
}
}
Output:
====Using for-each loop==== Key:= 1 , Value:= Parrot Key:= 2 , Value:= Falcon Key:= 3 , Value:= Swans Key:= 4 , Value:= Woodpecker Key:= 5 , Value:= Owl ====Using Iterator==== Key:= 1 , Value:= Parrot Key:= 2 , Value:= Falcon Key:= 3 , Value:= Swans Key:= 4 , Value:= Woodpecker Key:= 5 , Value:= Owl ====Using forEach method of Java 8==== Key:= 1 , Value:= Parrot Key:= 2 , Value:= Falcon Key:= 3 , Value:= Swans Key:= 4 , Value:= Woodpecker Key:= 5 , Value:= Owl ====Iterating over just keys==== Key:= 1 Key:= 2 Key:= 3 Key:= 4 Key:= 5 ====Iterating over just values==== Value:= Parrot Value:= Falcon Value:= Swans Value:= Woodpecker Value:= Owl:
Like other classes, the HashMap class also has a list of methods available for use. Let’s check out what are the varied methods under the HashMap class.
HashMap Methods | Description | |
---|---|---|
1 | void clear() | It removes all the key-value pair mappings from the specified Map. |
2 | int size() | It returns us the number of entries available in the specified Map. |
3 | Boolean isEmpty() | It used to check if the specified Map is empty or not. If there are any key and value pairs available then the function returns false else true. |
4 | Set entrySet() | It returns the collection outlook of the key-value pair mappings present in the specified Map. |
5 | Set keyset() | It returns the collection outlook or in simple words a set view of the keys present in the specified Map. |
6 | Value put(Objecy key, Object value) | It is used to insert a key-value pair mapping into the specified Map. |
7 | void putAll(Map map) | It is used to insert one particular map into another. |
8 | boolean containsValue(Object value) | It checks the mappings present in the specified map and returns true if there exists any value similar to the value being searched else return false. |
9 | boolean containsKey(Object key) | It checks the mappings present in the specified map and returns true if there exists any key similar to the key being searched else return false. |
10 | boolean equals(Object object) | It compares all the values present in the Map with the specified object and returns true if an exact match is found else returns false. |
11 | boolean remove(Object key) | It is used to delete an entry for the specified key. |
12 | Object clone() | It returns a shallow copy of the HashMap instance. |
That’s all about Java HashMap Example and its methods.
So, in this tutorial we have learnt about what a HashMap is and the various methods to iterate and print a HashMap.
We also had a short ride to the methods supported by the HashMap class and got to know their basic usage.
Now, we will learn about how to use the HashMap methods while coding.
Let us now look into few of the code examples of the methods that HashMap class supports. These methods help us in performing varied different operations on the map.
One can access the elements in a map using entrySet()
, keySet()
and values()
method.
import java.util.HashMap;
public class HashMapExample {
public static void main (String []args) {
HashMap<Integer, String> airlinesMap = new HashMap<>();
//Adding elements in HashMap.
airlinesMap.put(1, "Air India");
airlinesMap.put(2,"Emirates Airlines");
airlinesMap.put(3, "Qantas Airways");
//Printing the HashMap.
System.out.println("Airlines HashMap:= "+airlinesMap);
//Accessing all the key-value pair using entrySet()
System.out.println("Key-Value Mappings:= "+airlinesMap.entrySet());
//Accessing all the keys in the HashMap.
System.out.println("Keys:= " +airlinesMap.keySet());
//Accessing all the values in the HashMap.
System.out.println("Values:= " +airlinesMap.values());
}
}
Output:
The output of the above program would be:
Airlines HashMap:= {1=Air India, 2=Emirates Airlines, 3=Qantas Airways} Key-Value Mappings:= [1=Air India, 2=Emirates Airlines, 3=Qantas Airways] Keys:= [1, 2, 3] Values:= [Air India, Emirates Airlines, Qantas Airways]
One can insert elements into HashMap with the help of put(), putAll() and putIfAbsent().
import java.util.HashMap;
public class HashMapExample {
public static void main (String []args) {
HashMap<Integer, String> vowels = new HashMap<>();
//Adding elements in HashMap.
vowels.put(1, "A");
vowels.put(2, "E");
vowels.put(3, "I");
//Adding new elements if not present.
vowels.putIfAbsent(4, "O");
vowels.putIfAbsent(5, "U");
//Printing the vowels HashMap.
System.out.println("Vowels HashMap:= "+vowels);
//Creating HashMap of alphabets.
HashMap<Integer, String> alphabets = new HashMap<>();
alphabets.put(6, "B");
alphabets.putAll(vowels);
//Printing the alphabets HashMap.
System.out.println("Alphabets HashMap:= "+alphabets);
}
}
Output:
The output of the above program would be:
Vowels HashMap:= {1=A, 2=E, 3=I, 4=O, 5=U} Alphabets HashMap:= {1=A, 2=E, 3=I, 4=O, 5=U, 6=B}
One can remove elements from a HashMap with the help of remove(key)
and remove(key,value)
.
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> airlinesMap = new HashMap<>();
//Adding elements in HashMap.
airlinesMap.put(1, "Air India");
airlinesMap.put(2,"Emirates Airlines");
airlinesMap.put(3, "Qantas Airways");
airlinesMap.put(4,"Vistara");
//Printing the HashMap.
System.out.println("Airlines HashMap:= "+airlinesMap);
// remove method with single parameter
airlinesMap.remove(3);
System.out.println("Current entries in Map: " +airlinesMap);
// remove method with two parameters
airlinesMap.remove(2,"Emirates Airlines");
System.out.println("Updated HashMap: " + airlinesMap);
}
}
Output:
Airlines HashMap:= {1=Air India, 2=Emirates Airlines, 3=Qantas Airways, 4=Vistara} Current entries in Map: {1=Air India, 2=Emirates Airlines, 4=Vistara} Updated HashMap: {1=Air India, 4=Vistara}
Few other operations that we can do using HashMap methods are:
Below is the example that shows the usage of the above listed methods.
import java.util.HashMap;
public class HashMapExample {
public static void main(String [] args){
HashMap<Integer, String> vowels = new HashMap<>();
HashMap<Integer, String> alphabets = new HashMap<> ();
//Adding elements in HashMap.
vowels.put(1, "A");
vowels.put(2, "E");
vowels.put(3, "I");
vowels.put(4, "O");
vowels.put(5, "U");
//Checking if the above created maps are empty of not.
System.out.println("Is vowels HashMap empty:= " + vowels.isEmpty());
System.out.println("Is alphabets HashMap empty:= " + alphabets.isEmpty());
//Printing the size of vowels HashMap.
System.out.println("The size of vowels HashMap is:= " + vowels.size());
//Cloning Vowels HashMap to Alphbets HashMap.
alphabets = (HashMap)vowels.clone();
//Printing the vowels HashMap.
System.out.println("Vowels HashMap:= "+vowels);
//Printing the alphabets HashMap.
System.out.println("Alphabets HashMap:= "+alphabets);
//Checking if Vowels HashMap contains key '2'.
System.out.println("Vowels HashMap contains key '2':= "+vowels.containsKey(2));
//Checking if Alphabets HashMap contains value 'B'.
System.out.println("Vowels HashMap contains value 'B':= " +vowels.containsValue("B"));
//Clearing all elements in Vowels HashMap.
vowels.clear();
System.out.println("Vowels HashMap after clearing all elements:= " +vowels);
}
}
Output:
The output of the above program is:
Is vowels HashMap empty:= false Is alphabets HashMap empty:= true The size of vowels HashMap is:= 5 Vowels HashMap:= {1=A, 2=E, 3=I, 4=O, 5=U} Alphabets HashMap:= {1=A, 2=E, 3=I, 4=O, 5=U} Vowels HashMap contains key '2':= true Vowels HashMap contains value 'B':= false Vowels HashMap after clearing all elements:= {}
That’s all about the methods of HashMap class and Java HashMap example explained in detail.
If you have any questions on Java HashMap or thought about this tutorial, write me a comment below.
Happy Learning !