$show=/label

Java HashMap with Example Programs + Java 8 Methods

SHARE:

A quick guide to Java API HashMap methods and Understand how it works internally with examples.

1. Introduction


In this tutorial, We'll be learning HashMap API and its usage. HashMap is one of the implementations of the Map interface. HashMap is widely used in the realtime applications to store the key-value pair. This supports all kinds of operations needed on a daily basis to work on the dataset. This comes with most used built-in utility methods to add the values into map(), replace(), remove(), get() methods. We'll be showing java 8 new API changes to the HashMap such as compute(), replaceAll(), computeIfAbsent(), computeIfPresent(), merge() methods.

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable



Examples of HashMap In Java and Understand HashMap Real-Time usage



HashMap helps one object as an index to another object as the value. List index will be always a number whereas in Map it can be String, Integer, Float or Student or Trade objects.

Let us explore the most useful methods step by step.



2. HashMap Important Features


You should know and understand the characteristics of HashMap before using it. If your requirement is different then do not store the values into Map.


  • HashMap takes values always as key-value pairs. If you pass only one value, it will produce a compile-time error. If you do not want to store only one value then you need to pass the value as null.
  • HashMap does not preserve the insertion order of values. When you print it, it will print in a different order.
  • HashMap does not allow adding the same key multiple times. That means no duplicate keys are allowed.
  • HashMap maintains always key is unique.
  • HashMap allows only one null key. But, values can be null for multiple keys.
  • HashMap is not synchronized.
  • HashMap default size is 16 and the load factor is 0.75
  • HashMap internally uses LinkedList to store the key-value paint in the Node object.
  • HashMap gets the value in constant time.


3. HashMap Methods


HashMap has many methods as below.


    1. clear(): This removes all key/value pairs from map
    2. clone(): Create a shallow copy of the map but key and values will be not be cloned.
    3. compute(): This allows to do modifications to values when working with Stream API
    4. containsKey(Object key): Checks the given key is present in the map or not.
    5. containsValue(Object value):  Returns true if this map maps one or more keys to the specified value.
    6. entrySet(): Returns set with Entry&lt;K, V&gt; objects.
    7. forEach(): Forms the given logic on all values in the map
    8. get(Object Key): To get the value for a key
    9. isEmpty(): Returns true if this map contains no key-value mappings.
    10. keySet(): Returns Set&lt;K&gt; of keys in the map.
    11. merge(K k, V v, BiFuction b): If the key exists then it applied the bi function logic and updates the value in the map. Returns new updated value.
    12. put(K key, V value): Added new value to the map
    13. putAll(Map m): Adds all values from another map to the current map.
    14. putIfAbsent(K key, V value): If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
    15. remove(Object key): Removes the mapping for the specified key from this map if present.
    16. remove(Object key, Object value): Remove the key if the value is given. Otherwise do not delete.
    17. replace(K key, V value): Replaces the old value with the new value
    18. replace(K key, V oldValue, V newValue): Replace if the oldValue is matched to the existing value in the map for a given key.
    19. replaceAll(BiFunction function): Replace all values with the function output.
    20. size(): Returns size of entry objects (number of key-value pairs)
    21. values(): Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.


4. How to Create HashMap Objects


HashMap API gives 4 types of constructors and based on the need you can choose the right one.


  • Create HashMap with default size and load factor
  • Create with a preallocated memory
  • Create a new Map from an existing Map
  • Create with new default size and load factor

// creating map
HashMap<String, String> map = new HashMap<>();

// with preallocated capacity
HashMap<String, String> mapWithCapacity = new HashMap<>(200);

// From already existing map
HashMap<String, String> mapFromExistingMap = new HashMap<>(map);

// with capacity and load factor
HashMap<String, String> mapWithFactor = new HashMap<>(100, 0.5f);

5. Adding values to HashMap


Map API has two methods to add values to it and those are put() and putAll() methods.

put(Object key, Object value): This method stores one key-value pair at a time
putAll(): This adds another map to this map.

HashMap<String, String> idNamesMap = new HashMap<>();

idNamesMap.put("100", "Jhon");
idNamesMap.put("200", "Paul");
idNamesMap.put("300", "Tina");
idNamesMap.put("400", "Chunn");
idNamesMap.put("500", "menoj");

System.out.println("idNamesMap : " + idNamesMap);
HashMap<String, String> newIdNamesMap = new HashMap<>();
newIdNamesMap.put("600", "Zumba");
newIdNamesMap.putAll(idNamesMap);

System.out.println("newIdNamesMap : " + newIdNamesMap);

Output:


idNamesMap : {100=Jhon, 200=Paul, 300=Tina, 400=Chunn, 500=menoj}
newIdNamesMap : {100=Jhon, 200=Paul, 300=Tina, 400=Chunn, 500=menoj, 600=Zumba}

5. Getting the values from HashMap


get(Object key) will help to get the value for a given key. If the key is not on the map then it returns a null value. If null is returned means that key is not present in the map. null may be added explicitly to the map.

String value1 = newIdNamesMap.get("200");
System.out.println("value 1 : " + value1);

String value2 = newIdNamesMap.get("300");
System.out.println("value 2 : " + value2);

String value3 = newIdNamesMap.get("600");
System.out.println("value 3 : " + value3);

String nullValue = newIdNamesMap.get("800");
System.out.println("nullValue : " + nullValue);

String nullkeyValue = newIdNamesMap.get(null);
System.out.println("nullkeyValue : " + nullkeyValue);

Output:

value 1 : Paul
value 2 : Tina
value 3 : Zumba
nullValue : null
nullkeyValue : null

getOrDefault(Object key, V defaultValue)


Returns a value from the map if the key is found. If the key not found in the map then return the default mp specified.

String defaultValueNotFound = newIdNamesMap.getOrDefault("800", "Eight Hundread");
System.out.println("Get default vaue example key not found: " + defaultValueNotFound);

String defaultValueFound = newIdNamesMap.getOrDefault("400", "Four Hundread");
System.out.println("Get default vaue example : " + defaultValueFound);

Output:



Get default vaue example key not found: Eight Hundread
Get default vaue example : Chunn


6. Removing the key-value pair or Removing all values from Map


6.1 remove(Object key) Example

Use remove(Object key) method to remove a specific key from the map and returns the removed key's value. If the key is not present in the map then it returns null.

String removedValueForkey500 = newIdNamesMap.remove("500");
System.out.println("Removed value for the key 500 : " + removedValueForkey500);

String removedValueForkey1000 = newIdNamesMap.remove("1000");
System.out.println("Removed value for key 1000 : " + removedValueForkey1000);

Output:


Removed value for the key 500 : menoj
Removed value for key 1000 : null

6.2 clear() Example


Use clear() method to remove all key-value pairs from the map. After calling clear() method, Map will be having no values and the size will become 0.

newIdNamesMap.clear();

int size = newIdNamesMap.size();

System.out.println("Size after calling clear() method : " + size);

Output:

Size after calling clear() method : 0

7. Check Key or Value present in the Map


Map has two methods to check whether key or value presents in the map or not.

7.1 containsKey​(Object key)


This method takes a key as an argument and returns true if the key is found else false.

7.2 containsValue​(Object value)


This method takes the value as an argument and returns true if the key is found else false.

boolean key500exists = idNamesMap.containsKey("500");
boolean key900exists = idNamesMap.containsKey("900");

System.out.println("key 500 exists : " + key500exists);
System.out.println("key 900 exists : " + key900exists);

boolean valueZumbaexists = idNamesMap.containsKey("Zumba");
boolean valueBalajiexists = idNamesMap.containsKey("Balaji");

System.out.println("value Zumba exists : " + valueZumbaexists);
System.out.println("value Balaji exists : " + valueBalajiexists);

Output:



key 500 exists : true
key 900 exists : false
value Zumba exists : false
value Balaji exists : false

8. Getting all keys or values or Entry objects


Map has three methods that return all keys, values and Entry objects.

8.1 keySet()


Returns a Set<K> of keys that map have. This set is backed by Map object. If any changes to Set that are reflected immediately in the Map. As well as if any change to the map will be reflected in the Set.

Set<String> keysSet = newIdNamesMap.keySet();
System.out.println("keysSet : " + keysSet);

newIdNamesMap.put("1000", "google");
System.out.println("Checking modifications in keysSet : " + keysSet);

Output:

keysSet : [100, 200, 300, 400, 600]
Checking modifications in keysSet : [100, 200, 300, 400, 600, 1000]

8.2 values()


values() method returns Collection&lt;V&gt; with all values from Map.  If any changes to Collection that are reflected immediately in the Map. As well if any change to the map will be reflected in the Collection.

Collection can be anything such as AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue, ArrayDeque, ArrayList, AttributeList, BeanContextServicesSupport, BeanContextSupport, ConcurrentHashMap.KeySetView, ConcurrentLinkedDeque, ConcurrentLinkedQueue, ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet, DelayQueue, EnumSet, HashSet, JobStateReasons, LinkedBlockingDeque, LinkedBlockingQueue, LinkedHashSet, LinkedList, LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue, RoleList, RoleUnresolvedList, Stack, SynchronousQueue, TreeSet, Vector.

Collection<String> valuesCollection = newIdNamesMap.values();
System.out.println("values : " + valuesCollection);

newIdNamesMap.put("2000", "bing");
System.out.println("Checking modifications in Collection: " + valuesCollection);

Output:

values  : [Jhon, Paul, Tina, Chunn, Zumba, google]
Checking modifications in Collection: [Jhon, Paul, Tina, Chunn, Zumba, google, bing]

8.3 entrySet()


This method returns Set<Map.Entr<K,V>>; means all Entry&lt;K, V&gt; objects. HashMap all key values are stored in Entry objects. If any additions or removals to the original map
, all the changes are applied to Entry Set also.

public Set<Map.Entry<K,V>> entrySet()

9. compute()


compute() method is very useful when working with streams API.

public V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)

BiFunction logic will be executed for each key-value pair and new value will be updated in the map.


String returnedValue = newIdNamesMap.compute("300",
  (k, v) -> (v == null ? "value is null" : "key " + k + " value is : " + v));

System.out.println("compute returnedValue : " + returnedValue);

String returnedValueNull = newIdNamesMap.compute("8900",
  (k, v) -> (v == null ? "value is null" : "key " + k + " value is : " + v));

System.out.println("compute returnedValue for key 8900 : " + returnedValueNull);

System.out.println("map values after calling compute(): " + newIdNamesMap);

Output:


compute returnedValue : key 300 value is : Tina
compute returnedValue for key 8900 : value is null
map values after calling compute(): {100=Jhon, 200=Paul, 300=key 300 value is : Tina, 400=Chunn, 600=Zumba, 1000=google, 2000=bing, 8900=value is null}

Here, There are two situations that if the key exists in the map or not present in the map.

If you know that key always exists then use a compute specific method computeIfPresent(), if the key is not present always then use computeIfAbsent().

String returnedValueKeyPresent = newIdNamesMap.computeIfPresent("400", (k, v) -> (v + " updated"));

System.out.println("returnedValueKeyPresent : " + returnedValueKeyPresent);

String returnedValueKeyNotPresent = newIdNamesMap.computeIfAbsent("4500", (k) -> ("4500 added"));

System.out.println("returnedValueKeyPresent : " + returnedValueKeyNotPresent);

System.out.println("Chages to original map : " + newIdNamesMap);

Output:

returnedValueKeyPresent : Chunn updated
returnedValueKeyPresent : 4500 added
Chages to original map : {100=Jhon, 200=Paul, 300=key 300 value is : Tina, 400=Chunn updated, 600=Zumba, 1000=google, 4500=4500 added, 2000=bing, 8900=value is null}

10. Replacing Values


Replacing a specific key with a new value can be done using a map replace(k,v) method.

replace(k,v) method will replace the existing value with the new value. If key is not found then no value will be updated. This meturns the previous value.

public boolean replace(K key, V oldValue, V newValue): Replaces the entry for the specified key only if currently mapped to the specified value.

public void replaceAll(BiFunction<? super K,? super V,? extends V> function): Replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception. Exceptions thrown by the function are relayed to the caller.


HashMap<Integer, String> freshMap = new HashMap<>();

freshMap.put(100, "Jhon");
freshMap.put(200, "Paul");
freshMap.put(300, "Tina");
freshMap.put(400, "Chunn");
freshMap.put(500, "menoj");

freshMap.replace(500, "500");
freshMap.replace(700, "700");

System.out.println("freshMap : " + freshMap);

freshMap.replace(100, "Jhon", "100");
freshMap.replace(200, "Jhon", "200");

System.out.println("freshMap : " + freshMap);

freshMap.replaceAll((k, v) -> k + v);

System.out.println("freshMap : " + freshMap);

Output:

freshMap : {400=Chunn, 100=Jhon, 500=500, 200=Paul, 300=Tina}
freshMap : {400=Chunn, 100=100, 500=500, 200=Paul, 300=Tina}
freshMap : {400=400Chunn, 100=100100, 500=500500, 200=200Paul, 300=300Tina}

11. Map Iteration using forEach()


public void forEach(BiConsumer<? super K,? super V> action): Performs the given action for each entry in this map until all entries have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of entry set iteration (if an iteration order is specified.) Exceptions thrown by the action are relayed to the caller.

This is similar to the enhanced for each loop in java 8.

freshMap.forEach((k, v) -> System.out.println("key : " + k + ", value : " + v));

Output:


key : 400, value : 400Chunn
key : 100, value : 100100
key : 500, value : 500500
key : 200, value : 200Paul
key : 300, value : 300Tina

12. HashMap Full Example Program


Below is the complete program that contains all example code snipper and available on GitHub as well.

package com.java.w3schools.blog.hashmap;

import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

public class HashMapExamples {

 public static void main(String[] args) {

  // creating map
  HashMap<String, String> map = new HashMap<>();

  // with preallocated capacity
  HashMap<String, String> mapWithCapacity = new HashMap<>(200);

  // From already existing map
  HashMap<String, String> mapFromExistingMap = new HashMap<>(map);

  // with capacity and load factor
  HashMap<String, String> mapWithFactor = new HashMap<>(100, 0.5f);

  // creating map
  HashMap<String, String> idNamesMap = new HashMap<>();

  idNamesMap.put("100", "Jhon");
  idNamesMap.put("200", "Paul");
  idNamesMap.put("300", "Tina");
  idNamesMap.put("400", "Chunn");
  idNamesMap.put("500", "menoj");

  System.out.println("idNamesMap : " + idNamesMap);
  HashMap<String, String> newIdNamesMap = new HashMap<>();
  newIdNamesMap.put("600", "Zumba");
  newIdNamesMap.putAll(idNamesMap);

  System.out.println("newIdNamesMap : " + newIdNamesMap);

  String value1 = newIdNamesMap.get("200");
  System.out.println("value 1 : " + value1);

  String value2 = newIdNamesMap.get("300");
  System.out.println("value 2 : " + value2);

  String value3 = newIdNamesMap.get("600");
  System.out.println("value 3 : " + value3);

  String nullValue = newIdNamesMap.get("800");
  System.out.println("nullValue : " + nullValue);

  String defaultValueNotFound = newIdNamesMap.getOrDefault("800", "Eight Hundread");
  System.out.println("Get default vaue example key not found: " + defaultValueNotFound);

  String defaultValueFound = newIdNamesMap.getOrDefault("400", "Four Hundread");
  System.out.println("Get default vaue example : " + defaultValueFound);

  String nullkeyValue = newIdNamesMap.get(null);
  System.out.println("nullkeyValue : " + nullkeyValue);

  String removedValueForkey500 = newIdNamesMap.remove("500");
  System.out.println("Removed value for the key 500 : " + removedValueForkey500);

  String removedValueForkey1000 = newIdNamesMap.remove("1000");
  System.out.println("Removed value for key 1000 : " + removedValueForkey1000);

  // newIdNamesMap.clear();

  int size = newIdNamesMap.size();

  System.out.println("Size after calling clear() method : " + size);

  boolean key500exists = idNamesMap.containsKey("500");
  boolean key900exists = idNamesMap.containsKey("900");

  System.out.println("key 500 exists : " + key500exists);
  System.out.println("key 900 exists : " + key900exists);

  boolean valueZumbaexists = idNamesMap.containsKey("Zumba");
  boolean valueBalajiexists = idNamesMap.containsKey("Balaji");

  System.out.println("value Zumba exists : " + valueZumbaexists);
  System.out.println("value Balaji exists : " + valueBalajiexists);

  Set<String> keysSet = newIdNamesMap.keySet();
  System.out.println("keysSet : " + keysSet);

  newIdNamesMap.put("1000", "google");
  System.out.println("Checking modifications in keysSet : " + keysSet);

  Collection<String> valuesCollection = newIdNamesMap.values();
  System.out.println("values  : " + valuesCollection);

  newIdNamesMap.put("2000", "bing");
  System.out.println("Checking modifications in Collection: " + valuesCollection);

  // compute examples.

  String returnedValue = newIdNamesMap.compute("300",
    (k, v) -> (v == null ? "value is null" : "key " + k + " value is : " + v));

  System.out.println("compute returnedValue : " + returnedValue);

  String returnedValueNull = newIdNamesMap.compute("8900",
    (k, v) -> (v == null ? "value is null" : "key " + k + " value is : " + v));

  System.out.println("compute returnedValue for key 8900 : " + returnedValueNull);

  System.out.println("map values after calling compute(): " + newIdNamesMap);

  String returnedValueKeyPresent = newIdNamesMap.computeIfPresent("400", (k, v) -> (v + " updated"));

  System.out.println("returnedValueKeyPresent : " + returnedValueKeyPresent);

  String returnedValueKeyNotPresent = newIdNamesMap.computeIfAbsent("4500", (k) -> ("4500 added"));

  System.out.println("returnedValueKeyPresent : " + returnedValueKeyNotPresent);

  System.out.println("Chages to original map : " + newIdNamesMap);

  HashMap<Integer, String> freshMap = new HashMap<>();

  freshMap.put(100, "Jhon");
  freshMap.put(200, "Paul");
  freshMap.put(300, "Tina");
  freshMap.put(400, "Chunn");
  freshMap.put(500, "menoj");

  freshMap.replace(500, "500");
  freshMap.replace(700, "700");

  System.out.println("freshMap : " + freshMap);

  freshMap.replace(100, "Jhon", "100");
  freshMap.replace(200, "Jhon", "200");

  System.out.println("freshMap : " + freshMap);

  freshMap.replaceAll((k, v) -> k + v);

  System.out.println("freshMap : " + freshMap);

  freshMap.forEach((k, v) -> System.out.println("key : " + k + ", value : " + v));

 }

}

13. Conclusion


In this article, We have covered the HashMap APi and its methods with example programs.

GitHub

Ref

Java Iterator

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java HashMap with Example Programs + Java 8 Methods
Java HashMap with Example Programs + Java 8 Methods
A quick guide to Java API HashMap methods and Understand how it works internally with examples.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEguRKP-v7kr5YhGfgkLi1mgmI6YEKufCwK09ZBLQ_VR-zvGWRmhIWkZX26zJ-7slx5Qfz_-ZU_8tizXYwOi-otjhppBStBa2F9QLkZdrInIOh3MAmqHQge0F0kvDVBjwW8DUSN17TDMuMc/s640/Examples+of+HashMap+In+Java+and+Understand+HashMap+Real-Time+usage.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEguRKP-v7kr5YhGfgkLi1mgmI6YEKufCwK09ZBLQ_VR-zvGWRmhIWkZX26zJ-7slx5Qfz_-ZU_8tizXYwOi-otjhppBStBa2F9QLkZdrInIOh3MAmqHQge0F0kvDVBjwW8DUSN17TDMuMc/s72-c/Examples+of+HashMap+In+Java+and+Understand+HashMap+Real-Time+usage.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/04/java-hashmap.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/04/java-hashmap.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content