Java HashMap is an unordered key-value pair mappings collection, implementation of java.util.Map interface and is a part of the Java Collections framework

HashMap has the following attributes

  • Backed by hash table data structure

  • No guarantees to the iteration order

  • No duplicate keys. Permits null key and null value

  • Offers constant time performance for get and put operations, assuming the hash function distributes the elements properly among the buckets

  • Unsynchronized implementation. In multi-threading environment with at least one thread modifies the list, it must be synchronized externally

The below examples give you basic usages of HashMap. Some of the outputs may be different on your side as HashMap has no guarantees to the iteration order


You can learn using HashMap in more details with these tutorials

  • Create and Initialize a HashMap by using its constructors, Collection's util methods and Java 9+ Map.of methods

  • Iterate a HashMap by using for-each loop and Java 8+ forEach default method of Map and Iterable interfaces to iterate over HashMap's entrySet(), keySet() and values()

  • Query a HashMap including get all HashMap keys and values, get value by the specified key, check if key or value existing, get size and check if the HashMap is empty

  • Modify a HashMap by using put methods to add key-value pairs, replace methods to update values and remove methods to remove entries

  • Sort a HashMap by using TreeMap, TreeSet and ArrayList