Tuesday 30 July 2013

How to get and put value in HashMap in Generic way

1. Creating a class with main method, and defining your own method to put and get value from hashmap. HashMap as we know is a pair of key and values so K is as Key and V is representing Value with correspondent key.


package tts.test.hashmap;

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

public class TestMap<K, V> {

Map<K, V> map = new HashMap<>();
public V putInToHashMap(K key, V value) {
return map.put(key, value);

}
public V getValueFromHashMap(K key) {
return map.get(key);

}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
TestMap map= new TestMap<>();
map.putInToHashMap("Bharat", 11223344);
map.putInToHashMap("KDS", 22334455);
map.putInToHashMap("Dipak", 33445566);
map.putInToHashMap("Santosh", 44556677);
map.putInToHashMap("Umesh", 55667788);
System.out.println("Element  is :"+map.getValueFromHashMap("Bharat"));
}

}


2. Output
Element  is :11223344

Thank You

No comments:

Post a Comment