Agenda

HashMap collection in java?

  • HashMap is Hash table based implementation of the Map interface.
  • HashMap provides constant-time performance for the basic operations like get & put.
  • HashMap based implementation is not thread safe.
    • In multi-threading environment, HashMap should be synchronized externally.
  • If multiple threads access a hashmap concurrently then HashMap must synchronized externally.

Class hierarchy of HashMap collection

Class hierarchy of HashMap collection
Fig 1: Class hierarchy of HashMap collection

Put elements to HashMap Collection

Methods to insert or add elements to HashMap:

No.Method Name Description
1V put(K key, V value) Associates the specified value with the specified key in this map.
2void putAll(Map<? extends K,? extends V> m) Copies all of the mappings from the specified map to this map.
3default V 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.

Program: Put or Insert objects to HashMap collection (java /example)

package org.learn.collection.map.hmap;

import java.util.HashMap;
import java.util.Map;

public class DemoPutToHashMap {

 public static void main(String[] args) {
  Map<String, String> mapSportsPersonality = new HashMap<>();
  System.out.println("Demo of put methods of HashMap collection: ");
  demoPutMethod(mapSportsPersonality);
 }

 private static void demoPutMethod(Map<String, String> mapSportsPersonality) {
  System.out.println("1. Orignal HashMap:\n" + mapSportsPersonality);
  
  mapSportsPersonality.put("Tennis", "Federer");
  mapSportsPersonality.put("Cricket", "Bradman");
  System.out.println("2. Added Tennis &  Cricket using put: \n" + mapSportsPersonality);

  Map<String, String> newSportsMap = new HashMap<>();
  newSportsMap.put("Golf", "Woods");
  newSportsMap.put("Boxer", "Ali");

  mapSportsPersonality.putAll(newSportsMap);
  System.out.println("3. Added another map using putAll to map:\n" + mapSportsPersonality);

  mapSportsPersonality.putIfAbsent("Baseball", "Trout");

  // key Baseball already added to map, so "Kershaw" would not be added
  mapSportsPersonality.putIfAbsent("Baseball", "Kershaw");
  System.out.println("4. Added Baseball using putIfAbsent to map:\n" + mapSportsPersonality);
 }
}

Output: insert string objects to HashMap (java /example)

Demo of put methods of HashMap collection: 
1. Orignal HashMap:
{}
2. Added Tennis &  Cricket using put: 
{Tennis=Federer, Cricket=Bradman}
3. Added another map using putAll to map:
{Tennis=Federer, Cricket=Bradman, Golf=Woods, Boxer=Ali}
4. Added Baseball using putIfAbsent to map:
{Tennis=Federer, Cricket=Bradman, Golf=Woods, Baseball=Trout, Boxer=Ali}

putIfAbsent method of HashMap

  • putIfAbsent method is defined in Map interface.
  • putIfAbsent method is used to add entry to HashMap, if its not present in HashMap.

Prototype of putIfAbsent method

Method Name Description
default V 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.

Program – putIfAbsent method of HashMap in java

package org.learn.collection.map.hmap;

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;

public class DemoPutIfAbsentHashMap {

 public static void main(String[] args) {
  Map<String, String> mapSportsPersonality = new HashMap<>();
  mapSportsPersonality.put("Tennis", "Federer");
  mapSportsPersonality.put("baseball", "Trout");
  mapSportsPersonality.put("Basketball", "Jordan");
  mapSportsPersonality.put("Golf", "Woods");

  System.out.println("Demo of putIfAbsent method: ");
  demoPutIfAbsent(mapSportsPersonality);
 }

 private static void demoPutIfAbsent(Map<String, String> mapSportsPersonality) {
  System.out.println("1. Orignal HashMap:" + mapSportsPersonality);
  Map.Entry<String, String> newEntry = new AbstractMap.SimpleEntry<String, String>("Tennis", "Djokovic");

  System.out.println("2. New entry to add:\n" + newEntry);
  String existingValue = mapSportsPersonality.putIfAbsent(newEntry.getKey(), newEntry.getValue());
  if (null != existingValue) {
   System.out.println("Key :" + newEntry.getKey() + " already exists, Record not inserted");
   System.out.println("Entries in hashmap:" + mapSportsPersonality);
  } else {
   System.out.println("New record added to hashMap:\n"+mapSportsPersonality);
  }

  newEntry = new AbstractMap.SimpleEntry<String, String>("Boxer", "Ali");

  System.out.println("3. New entry to add:\n" + newEntry);
  existingValue = mapSportsPersonality.putIfAbsent(newEntry.getKey(), newEntry.getValue());
  if (null != existingValue) {
   System.out.println("Key :" + newEntry.getKey() + " already exists, Record not inserted");
   System.out.println("Entries in hashmap:" + mapSportsPersonality);
  } else {
   System.out.println("New record added to hashMap:\n" + mapSportsPersonality);
  }
 }
}

Output – putIfAbsent method of HashMap in java

Demo of putIfAbsent method: 
1. Orignal HashMap:{Tennis=Federer, Golf=Woods, baseball=Trout, Basketball=Jordan}
2. New entry to add:
Tennis=Djokovic
Key :Tennis already exists, Record not inserted
Entries in hashmap:{Tennis=Federer, Golf=Woods, baseball=Trout, Basketball=Jordan}
3. New entry to add:
Boxer=Ali
New record added to hashMap:
{Tennis=Federer, Golf=Woods, baseball=Trout, Basketball=Jordan, Boxer=Ali}

Iterate HashMap collection having string objects

  • We will iterate or loop through HashMap collection using following methods:
    • Iterate HashMap using forEach method of java 8
    • Iterate HashMap using entrySet Iterator.

Iterate HashMap collection having string objects (Java8)

package org.learn.collection.map.hmap;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class DemoIterationHashMap {

 public static void main(String[] args) {
  Map<String, String> mapSportsPersonality = new HashMap<>();
  mapSportsPersonality.put("Tennis", "Federer");
  mapSportsPersonality.put("Cricket", "Bradman");
  mapSportsPersonality.put("Basketball", "Jordan");
  mapSportsPersonality.put("Golf", "Woods");
  mapSportsPersonality.put("Boxer", "Ali");

  System.out.println("Demo: Iterate HashMap collection in java ");
  demoIterateMethod(mapSportsPersonality);
 }

 private static void demoIterateMethod(Map<String, String> mapSportsPersonality) {

  System.out.println("1. Iterate HashMap using forEach method:");
  // Output using Java 8
  mapSportsPersonality.forEach((key, value) -> {
   System.out.println("Game:" + key + ", Player:" + value);
  });

  System.out.println("\n2. Iterate HashMap collection using entrySet iterator:");
  // Output use Iterator:
  Set<Entry<String, String>> entrySet = mapSportsPersonality.entrySet();
  Iterator<Entry<String, String>> iterator = entrySet.iterator();
  while(iterator.hasNext()) {
   Map.Entry<String, String> entry = iterator.next();
   System.out.println("Game:" + entry.getKey() + ", Player:" + entry.getValue());
  }
 }
}

Output: Iterate HashMap collection having string objects 

Demo: Iterate HashMap collection in java 
1. Iterate HashMap using forEach method:
Game:Tennis, Player:Federer
Game:Cricket, Player:Bradman
Game:Golf, Player:Woods
Game:Basketball, Player:Jordan
Game:Boxer, Player:Ali

2. Iterate HashMap collection using entrySet iterator:
Game:Tennis, Player:Federer
Game:Cricket, Player:Bradman
Game:Golf, Player:Woods
Game:Basketball, Player:Jordan
Game:Boxer, Player:Ali

Remove elements/string objects from HashMap

Methods to remove elements or objects from HashMap collection

No.Method Name Description
1V remove(Object key) Removes the mapping for the specified key from this map if present.
2boolean remove(Object key, Object value) Removes the entry for the specified key only if it is currently mapped to the specified value.

We will demonstrate the removal of keys using entrySet iterator.

Program: remove elements objects from HashMap collection

package org.learn.collection.map.hmap;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class DemoRemoveHashMap {

 public static void main(String[] args) {
  Map<String, String> mapSportsPersonality = new HashMap<>();
  mapSportsPersonality.put("Tennis", "Federer");
  mapSportsPersonality.put("Cricket", "Bradman");
  mapSportsPersonality.put("Basketball", "Jordan");
  mapSportsPersonality.put("Golf", "Woods");
  mapSportsPersonality.put("Boxer", "Ali");

  System.out.println("Demo HashMap collection remove methods : ");
  demoRemoveMethod(mapSportsPersonality);
 }

 private static void demoRemoveMethod(Map<String, String> mapSportsPersonality) {
  // {Tennis=Federer, Cricket=Bradman, Golf=Woods, Basketball=Jordan, Boxer=Ali}
  System.out.println("1. Orignal hashmap:\n" + mapSportsPersonality);

  // Remove Cricket from map
  mapSportsPersonality.remove("Cricket");
  // {Tennis=Federer, Golf=Woods, Basketball=Jordan, Boxer=Ali}
  System.out.println("2. Removed Cricket from map : \n" + mapSportsPersonality);

  mapSportsPersonality.remove("Boxer","Ali");
  // {Tennis=Federer, Golf=Woods, Basketball=Jordan}
  System.out.println("3. Removed entry from map with Key=Boxer and Value=Ali:\n " + mapSportsPersonality);

  Set<Entry<String, String>> entrySet = mapSportsPersonality.entrySet();
  Iterator<Entry<String, String>> iterator = entrySet.iterator();
  while(iterator.hasNext()) {
   Map.Entry<String, String> entry = iterator.next();
   if (entry.getKey().equals("Basketball")) {
    iterator.remove();
   } else if (entry.getKey().equals("Golf")) {
    iterator.remove();
   }
  }
  // {Tennis=Federer}
  System.out.println("4. Removed Basketball,Golf during iteration:\n " + mapSportsPersonality);
 }
}

Output: remove elements objects from HashMap collection

Demo HashMap collection remove methods: 
1. Orignal hashmap:
{Tennis=Federer, Cricket=Bradman, Golf=Woods, Basketball=Jordan, Boxer=Ali}
2. Removed Cricket from map : 
{Tennis=Federer, Golf=Woods, Basketball=Jordan, Boxer=Ali}
3. Removed entry from map with Key=Boxer and Value=Ali:
 {Tennis=Federer, Golf=Woods, Basketball=Jordan}
4. Removed Basketball,Golf during iteration:
 {Tennis=Federer}

Sort HashMap by keys in java (ascending & descending order)

  • Sort the HashMap by keys in ascending & descending order.
    • Map<String, String> mapSportsPersonality = new HashMap<>().
  • Print the sorted map using forEach method (Java 8)

Program – sort HashMap by keys in ascending & descending order

package org.learn.collection.map.hmap;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SortElementInArrayList {

 public static void main(String[] args) {
  Map<String, String> mapSportsPersonality = new HashMap<>();
  mapSportsPersonality.put("Tennis", "Federer");
  mapSportsPersonality.put("Cricket", "Bradman");
  mapSportsPersonality.put("Basketball", "Jordan");
  mapSportsPersonality.put("Golf", "Woods");
  mapSportsPersonality.put("Boxer", "Ali");

  System.out.println("Demo of sort methods: ");
  demoSortMethod(mapSportsPersonality);  
 } 

 private static void demoSortMethod(Map<String, String> mapSportsPersonality) {
  // {Tennis=Federer, Cricket=Bradman, Golf=Woods, Basketball=Jordan, Boxer=Ali}
  System.out.println("Orignal HashMap:" + mapSportsPersonality);
  
  System.out.println("\n1. Sort HashMap by ascending keys: " );
  TreeMap<String,String>mapSorted = new TreeMap<>(mapSportsPersonality);
  mapSorted.forEach((key, value) -> {
   System.out.println(key + ", " + value);
  });
  
  System.out.println("\n2. Sort HashMap by descending keys: " );
  mapSorted.descendingMap().forEach((key, value) -> {
   System.out.println( key + ", "  + value);
  });  
 } 
}

Output – Sort HashMap in ascending & descending order

Demo of sort methods: 
Orignal HashMap:{Tennis=Federer, Cricket=Bradman, Golf=Woods, Basketball=Jordan, Boxer=Ali}

1. Sort HashMap by ascending keys: 
Basketball, Jordan
Boxer, Ali
Cricket, Bradman
Golf, Woods
Tennis, Federer

2. Sort HashMap by descending keys: 
Tennis, Federer
Golf, Woods
Cricket, Bradman
Boxer, Ali
Basketball, Jordan
Scroll to Top