Add Items

The HashMap class has many useful methods. For example, to add items to it, use the put() method:

{AB=Africa, SMITH=AUS, Kane=NZ, Virat=India}

Access an Item

To access a value in the HashMap, use the get() method and refer to its key:

Remove an Item

To remove an item, use the remove() method and refer to the key:

HashMap Size

To find out how many items there are, use the size() method:

Loop Through a HashMap

Loop through the items of a HashMap with a for-each loop.

Other Types

Keys and values in a HashMap are actually objects. In the examples above, we used objects of type “String”. Remember that a String in Java is an object (not a primitive type). To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:

Initial Map {1=Somnath, 2=Sachin, 3=You}Updated Map {1=Somnath 2=good, 3=You}
Initial Mappings are: {20=Sachin, 25=Welcomes, 10=Somnath, 30=You, 15=4}Is the key '20' present? trueIs the key '5' present? false



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store