Build Rest API from scratch in Node.js
July 24, 2020
4 min
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..).
HashMap<String, String> map = new HashMap<>();
map.put("name", "Arvind Pandey"); map.address("address", "Hyderabad"); System.out.println(map); // Prints => {address=Hyderabad, name=Arvind Pandey}
Values can be retrieved using key.
System.out.println(map.get("name")); // Prints => Arvind Pandey
map.remove("name");
map.clear();
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 }
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
Quick Links
Legal Stuff