Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Monday, November 22, 2021

Java HashMap with Example Programs + Java 8 Methods

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

No comments:

Post a Comment

Please do not add any spam links in the comments section.