HomeAbout Me

HashMap Fundamentals in Java

By Arvind Pandey
Published in Programming
May 13, 2020
1 min read

What is a HashMap

HashMap is one many data structures in programming. It stores data in key-value format. Like, name can be key and value can be the actual value. HashMap can be thought of an special case of Array. Arrays also store values using key-value pair, the only thing is, in Array we have different form of key (indexes - 0, 1, 2..).

How to declare HashMap

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

Store values in the HashMap

map.put("name", "Arvind Pandey");
map.address("address", "Hyderabad");
System.out.println(map); // Prints => {address=Hyderabad, name=Arvind Pandey}

Access values from HashMap

Values can be retrieved using key.

System.out.println(map.get("name")); // Prints => Arvind Pandey

Remove certain value from HashMap


Remove all values from HashMap


Loop through a HashMap

For-each loop can be used to loop through HashMap.

for(String key: map.keySet()) {
  System.out.println(key+ ", "); // Prints => address, name
for(String value: map.values()) {
  System.out.print(value+", "); // Prints => Hyderabad, Arvind Pandey
for(String key: map.keySet()) {
  System.out.print("key: "+key+", value: "+map.get(key)); // Prints key:value pair on different line

One more way to loop through HashMap

There is another way to loop over HashMap, using iterator.

Iterator itr = map.entrySet().iterator();
while(itr.hasNext()) {
  System.out.println(itr.next()); // Prints key=value pair on different line

That’s pretty much a very fundamental level about HashMap.

Hope you liked this tutorial. You might also like other tutorials in this series here


Previous Article
LinkedList fundamentals in Java


Life & Productivity

Related Posts

Build Rest API from scratch in Node.js
July 24, 2020
4 min
Arvind Pandey © 2022, All Rights Reserved.

Quick Links

About Me

Social Media