How to add elements in HashMap (Key/Value)
To add elements in HashMap we use V Map.put(K key, V value) method. Elements in Hashmap are added in a Key/Value pair.
Points to Remember about put() method
1. put() method maps the given key to the value. If a key already exits in the HashMap, then the old value is replaced with new value.
2. put() method returns the previously associated value for that Key. If the HashMap does not contain that key, then put() method returns a null value.
Example : Add Elements in HashMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | package com.kscodes.sampleproject; import java.util.HashMap; import java.util.Map; public class HashMapExample { public static void main(String[] args) { Map<String, String> hashMap = new HashMap<String, String>(); hashMap.put("USD", "American Dollar"); hashMap.put("AUD", "Australian Dollar"); hashMap.put("EUR", "Euro"); System.out.println("The HashMap has following elements::"); System.out.println(hashMap); System.out.println("*********************************"); System.out.println("Now trying to add a new element with a old key"); // Trying to add a new value with Key as "USD" String oldValue = hashMap.put("USD","United States of America Currency"); System.out.println("The Old Value of the Key 'USD' was ::" + oldValue); System.out.println("The HashMap now has following elements::"); System.out.println(hashMap); } } |
Output
1 2 3 4 5 6 7 | The HashMap has following elements:: {EUR=Euro, USD=American Dollar, AUD=Australian Dollar} ********************************* Now trying to add a new element with a old key The Old Value of the Key 'USD' was ::American Dollar The HashMap now has following elements:: {EUR=Euro, USD=United States of America Currency, AUD=Australian Dollar} |