Map is an interface which stores key and value. It has various types of implementations. One of those implementations is “HashMap”.
HashMap implementation includes the following built-in
functions listed below.
put(): adding key, value to the HashMap.
get(): This function gets the key and value.
containsKey(): This function checks a value is available or
not.
getKey(): It gets the key.
getValue() :It retrieves the value associated with the key.
remove() :This function deletes the entry.
size() :This gives you the size of the HashMap.
clear() :It clear all the keys and values.
isEmpty(): This returns Boolean value to check the HashMap
is empty or not.
Program:
import java.util.HashMap;
import java.util.Map;
public class HashMapEg {
public static void
main(String[] args) {
// Let us
create a HashMap
Map<String,
String> map1 = new HashMap<>();
//Insert the
values to the HashMap as key and value.
map1.put("Car", "Vehicle");
map1.put("Cricket", "Sports");
map1.put("Shirt", "Dress");
map1.put("Juice","Drink");
map1.put("Orange","Fruit");
// retrieve a
value by searching by key value
System.out.println("Car is a " + map1.get("Car"));
// checking
for an entry
if
(map1.containsKey("Cricket")) {
System.out.println("Cricket is present in the map.");
}
// Loop to
print the keys and values in the HashMap
for
(Map.Entry<String, String> entry : map1.entrySet()) {
System.out.println(entry.getKey() + " is a " +
entry.getValue());
}
// delete a
key and value
map1.remove("Fruit");
// print the
size of hashmap
System.out.println("Size of the map: " + map1.size());
// Clearing
all the key,value pair
map1.clear();
//Check for
map is empty or not
if(map1.isEmpty())
System.out.println("The map is empty" + map1.isEmpty());
}
}
Output:
C:\raji\blog>javac HashMapEg.java
C:\raji\blog>java HashMapEg
Car is a Vehicle
Cricket is present in the map.
Cricket is a Sports
Shirt is a Dress
Car is a Vehicle
Juice is a Drink
Orange is a Fruit
Size of the map: 5
The map is empty
This is the simple implementation of HashMap using java
programming. Hope this will be useful for you. Keep coding!!!
No comments:
Post a Comment