Generic Map In Java - GeeksforGeeks

29 Oct, 2020
Java Arrays store items in an ordered collection and the values can be accessed using the index(an integer). Whereas HashMap stores as a Key/ Value pair. Using HashMap, we can store the items or values and these values can be accessed by indexes/ keys of any type be it Integer, String, Double, Character, or any user-defined datatype.
The Mappings in a HashMap are from Key → Value
HashMap is a part of Java since Java 1.2. It implements java.util.Map interface.
What is Generic Map and how is it different from the term HashMap?
The term generic simply is the idea of allowing the type (Integer, Double, String, etc. or any user-defined type) to be the parameter to methods, class, or interface. For eg, all the inbuilt collections in java like ArrayList, HashSet, HashMap, etc. use generics. 
Generic Map in simple language can be generalized as:
Map< K, V > map = new HashMap< K, V >();

Where K and V are used to specify the generic type parameter passed in the declaration of a HashMap. We can add any type be it Integer, String, Float, Character, or any user-defined type in place of K and V in the above syntax to specify that we can initialize the HashMap of our wish.
Example:
Suppose if the key is of type String and the corresponding value is of type Integer, then we can initialize it as,
Map< String , Integer > map = new HashMap< String ,Integer >();

The map can now only accept String instances as key and Integer instances as values.
This can be done by using put() and get() function.
1. put(): Used to add a new key/value pair to the Hashmap.
2. get(): Used to get the value corresponding to a particular key.
Example :
Map< Integer, String > map = new HashMap<>();

// adding the key 123 and value
// corresponding to it as abc in the map
map.put( 123, "abc");     
map.put(65, "a");
map.put(2554 , "GFG");
map.get(65);

Output:
a

Map has two collections for iteration. One is keySet() and the other is values().
Example: Using iterator() method 
Map<Integer, Integer> map = new HashMap<>;

//adding key, value pairs to the Map

// iterate keys.
Iterator<Integer> key   = map.keySet().iterator();

while(key.hasNext()){
  Integer aKey   = key.next();
  String  aValue = map.get(aKey);
}

Iterator<Integer>  value = map.values().iterator();

while(valueIterator.hasNext()){
  String aString = value.next();
}

Example: Using new for-loop or for-each loop or generic for loop
Map<Integer, String> map = new HashMap<Integer, String>;

//adding key, value pairs to the Map

//using for-each loop
for(Integer key : map.keySet()) {
    String value = map.get(key);
    System.out.println("" + key + ":" + value);
}

for(String value : map.values()) {
    System.out.println(value);
}

Java Program to illustrate the usage of a map 
Java
// Java program to demonstrate// Generic Map  import java.io.*;import java.util.*;  class GenericMap {      public static void main(String[] args)    {        // create array of strings        String arr[]            = { "gfg",  "code",    "quiz",   "program",                "code", "website", "quiz",   "gfg",                "java", "gfg",     "program" };          // to count the frequency of a string and store it        // in the map        Map<String, Integer> map = new HashMap<>();        for (int i = 0; i < arr.length; i++) {            if (map.containsKey(arr[i])) {                int count = map.get(arr[i]);                map.put(arr[i], count + 1);            }            else {                map.put(arr[i], 1);            }        }          // to get and print the count of the mentioned        // string        System.out.println(map.get("gfg"));        System.out.println(map.get("code"));    }}
3
2
Java-Generics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
StringBuilder Class in Java with Examples
Comparator Interface in Java with Examples
Generics in Java
Functional Interfaces in Java
Java Programming Examples
HashMap get() Method in Java