Adds

Generic Map in Java Tutorial

Java Generics Tutorial List :

Generic Map in Java :

In this tutorial you will see how to create a generic Map object. In a generic Map you need to define the type of the key and the type of the value of object stored in the Map.you can set the specific type of both the keys and values in a generic Map instance.

The syntax for creating a generic Map is given below.

Map<k, v=""> map = new Map<k, v="">();

Here K is the type of map key and V is the type of the value stored in the map. If you want a map to hold a value of reference to String object and using an Integer as the key, declaration of Map is given below.

Map<Integer, String> set = new HashMap<Integer, String>;

This Map can now only accept Integer instances as keys, and String instances as values.


Adding and getting elements to a generic Map :

Adding and getting elements to a generic Map is done using the put() and get() methods,

If you want to add some elements to the map you can use put() method. No need to worry that you put a wrong type of object into the map,because the Java compiler will check it at compilation time.

Map <integer, string=""> map = new HashMap<>();

map.put(1, "A");

map.put(2, "B");

//map.put("4", new Date()); // Compile time error!

String a = map.get(1);

String b = map.get(2);

The get() method will return a value from the map that correspond with the given key. It is not necessary to cast the String instance returned by the get() method. The compiler knows that this Map has String values, so casting is not necessary.


Iterating a Generic Map :

You can iterate map by using two collections keySet and the values(). Most often you iterate the key Set and access the values for each key via the Map.get() method.

Using keySet() :

Map<integer, string=""> map = new HashMap<integer, string="">;

map.put(1, "A");

map.put(2, "B");

// iterate keys.

Iterator<integer> keyIterator = map.keySet().iterator();

while(keyIterator.hasNext()){

Integer aKey = iterator.next();

String aValue = map.get(aKey);

}

Using values() :

Map<integer, string=""> map = new HashMap<integer, string="">;

map.put(1, "A");

map.put(2, "B");

// iterate keys.

Iterator<string> valueIterator = map.values().iterator();

while(valueIterator.hasNext()){

String aString = valueIterator.next();

}

You can also use the new for-loop, like this:

Map<integer, string=""> map = new HashMap<integer, string="">;

//... add key, value pairs to the Map

for(Integer aKey : map.keySet()) {

String aValue = map.get(aKey);

System.out.println("" + aKey + ":" + aValue);

}

for(String aValue : map.values()) {

System.out.println(aValue);

}

Output

element is: Raj
Ravi
Raj

In Next Article we will discuss about Generics Map in java.




comments powered by Disqus