What is Hashmap in Java?

A HashMap basically designates unique keys to corresponding values that can be retrieved at any given point. Working with HashMap in Java

Features of Java Hashmap

a) The values can be stored in a map by forming a key-value pair. The value can be retrieved using the key by passing it to the correct method.

b) If no element exists in the Map, it will throw a ‘NoSuchElementException’.

c) HashMap stores only object references. That's why, it's impossible to use primitive data types like double or int. Use wrapper class (like Integer or Double) instead.

Working with HashMap in Java


Using HashMaps in Java Programs:

Following are the two ways to declare a Hash Map:
HashMap<String, Object> map = new HashMap<String, Object>();
HashMap<String, Object> map = new HashMap<>();

Important Hashmap Methods

  • get(Object KEY) – This will return the value associated with specified key in this Java hashmap.
  • put(Object KEY, String VALUE) – This method stores the specified value and associates it with the specified key in this map.

Java Hashmap Example

Following is a sample implementation of java Hash Map:
import java.util.HashMap;
import java.util.Map;
public class Sample_TestMaps{
  public static void main(String[] args){
    Map<String, String> objMap = new HashMap<String, String>();
    objMap.put("Name", "Suzuki");
    objMap.put("Power", "220");
    objMap.put("Type", "2-wheeler");
    objMap.put("Price", "85000");
    System.out.println("Elements of the Map:");
    System.out.println(objMap);
  }
}

Lets us ask a few queries to the Hash Map itself to know it better


Q: So Mr.Hash Map, how can I find if a particular key has been assigned to you?

A: Cool, you can use the containsKey(Object KEY) method with me, it will return a Boolean value if I have a value for the given key.

Q: How do I find all the available keys that are present in the Map?

A: I have a method called as keyset() that will return all the keys in the map. In the above example, if you write a line as – System.out.println(objMap.keySet());

It will return an output as-
[Name, Type, Power, Price]

Similarly, if you need all the values only, I have a method as values().
System.out.println(objMap.values());

It will return an output as-
[Suzuki, 2-wheeler, 220, 85000]

Q: Suppose, I need to remove only a particular key from the Map, do I need to delete the entire Map?

A: No buddy!! I have a method as remove(Object KEY) that will remove only that particular key-value pair.

Q: How can we check if you actually contain some key-value pairs?

A: Just check if I am empty or not!! In short, use isEmpty() method against me ;)

 

YOU MIGHT LIKE: