What is HashMap?
HashMap is a class of collections , it extends AbstractMap and implements Map interface.
HashMap is an unordered and unsorted Map means it does not guarantee the order of elements while retrieving.
HashMap allows one null key and multiple null values and does not allow duplicate keys. HashMap is not synchronized.
How to make HashMap synchronized?
We can make HashMap synchronized using the the below statement
Collections.synchronizedMap(<your hashmap reference>)
Inserting Data into HashMap
Data can be inserted into HashMap using put() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.*; public class HashMapDemo { public static void main(String[] args) { HashMap map = new HashMap(); map.put(1, "Akash"); map.put(2, "Ram"); map.put(3,"Neha" ); System.out.println("Maps :" +map); } } |
Output :
Maps : { 1=Akash, 2=Ram, 3=Neha }
Retrieving Data from HashMap
Data can be retrieved using get() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.*; public class HashMapDemo { public static void main(String[] args) { HashMap map = new HashMap(); map.put(1, "Akash"); map.put(2, "Ram"); map.put(3,"Neha" ); System.out.println("Maps :" +map); System.out.println(map.get(1)); } } |
Output:
Maps : { 1=Akash, 2=Ram, 3=Neha }
Akash
Iterating through HashMap
HashMap class does not implement Iterator interface, so we need to use entrySet() method to get the objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<strong>import</strong> java.util.*; <strong>public</strong> <strong>class</strong> HashMapDemo { public static void main (String [] args) { HashMap map = new HashMap(); map.put(1, "Akash"); map.put(2, "Ram"); map.put(3,"Neha" ); map.put(4, "Krishna"); map.put(5,"Hari"); for (Map.Entry<Integer,String> entry : map.entrySet()) { int key = entry.getKey(); System.out.print("Key is "+key); String value = entry.getValue(); System.out.println(" value is "+value); } } } |
Output:
Key is 1 value is Akash
Key is 2 value is Ram
Key is 3 value is Neha
Key is 4 value is Krishna
Key is 5 value is Hari
Leave a Reply