HashMap in java with examples

Previous
Next
HashMap is most common Collection which we use now a days. It stores entry in key value pair.
  1. HashMap implements Map interface which maps key to value.
  2. It is not synchronized and is not thread safe.
  3. Duplicate keys are not allowed
  4. One null key and multiple null values are allowed

Java HashMap tutorial:

Example:

When you run above program, you will get below output

Storing Custom objects as Key:

You can store custom objects as Key in HashMap but you should implement hashcode and equals method, otherwise it may not work as expected.  You may go through hashcode and equal method to understand it better.
Create a class called Country.java

Create another class HashMapMain.java

When you run above program, you will get below output

HashMap is not synchronized by default but we can make it synchronized using

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog