HashMap in java

In this tutorial we will learn HashMap .HashMap is the collection class .It is used to sort key and values pairs  HashMap <K, V> .HashMap implement Map Interface . HashMap not order key and values, also it allow Key null and values null .It is used for maintain Key and Value mapping in Java.

HashMap<K,V> hashmap = new HashMap<K,V>();

It is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap. It neither does any kind of sorting to the stored keys and Values. You must need to import java.util.HashMap or its super class in order to use the HashMap class and methods.

See Example:

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

public class Example {

public static void main(String[] args) {
HashMap<Integer, String>  hashMap = getHashMapKeyAndValue();
//For Loop hashMap
 System.out.println("For Loop:");
for(Map.Entry  map : hashMap.entrySet()){
System.out.println("Key :"+ map.getKey() + " & Value : " +map.getValue());
}
//WHILE LOOP & ITERATOR
        System.out.println("While Loop:");
     
        Iterator iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry map2 = (Map.Entry) iterator.next();
         System.out.println("Key: "+map2.getKey() + " & Value: " + map2.getValue());
       }

}
//Declare method
public static  HashMap<Integer, String> getHashMapKeyAndValue(){
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
hashMap.put(01, "Book1");
hashMap.put(05, "Book5");
hashMap.put(03, "Book3");
hashMap.put(04, "Book4");
hashMap.put(07, "Book7");
hashMap.put(02, "Book2");
hashMap.put(06, "Book6");
return hashMap;

}

}

//result :
For Loop:
Key :1 & Value : Book1
Key :2 & Value : Book2
Key :3 & Value : Book3
Key :4 & Value : Book4
Key :5 & Value : Book5
Key :6 & Value : Book6
Key :7 & Value : Book7
While Loop:
Key: 1 & Value: Book1
Key: 2 & Value: Book2
Key: 3 & Value: Book3
Key: 4 & Value: Book4
Key: 5 & Value: Book5
Key: 6 & Value: Book6
Key: 7 & Value: Book7





EmoticonEmoticon