Insert elements to HashMap collection in java (example)
Yogesh
What is 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 is not thread safe.
We would like to add or insert elements/objects to HashMap.
Class hierarchy of HashMap collection:
Methods to insert or add elements to HashMap:
No.
Method Name
Description
1
V put(K key, V value)
Associates the specified value with the specified key in this map.
2
void putAll(Map<? extends K,? extends V> m)
Copies all of the mappings from the specified map to this map.
3
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.
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: 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}