The Wayback Machine - https://web.archive.org/web/20240819220044/https://www.geeksforgeeks.org/generic-map-in-java/
Open In App

Generic Map In Java

Last Updated : 29 Oct, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Accessing A Generic Map

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

Iterating A Generic Map

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"));
    }
}


Output

3
2


Similar Reads

Non-generic Vs Generic Collection in Java
We will be discussing differences later prior let us understand what is generic Collection and non-generic Collection, and most importantly dealing with the implementation part as during implementation one can only really get the real understanding of the concept, henceforth the differences between them. Generics are basically the errors appearing
5 min read
Initialize a static Map using Java 9 Map.of()
In this article, a static map is created and initialised in Java using Java 9. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Java 9 feature - Map.of() method In Java 9, Map.of() was introduced which is a convenient way to create instances of Map
2 min read
Generic For Loop in Java
When we know that we have to iterate over a whole set or list, then we can use Generic For Loop. Java's Generic has a new loop called for-each loop. It is also called enhanced for loop. This for-each loop makes it easier to iterate over array or generic Collection classes. In normal for loop, we write three statements : for( statement1; statement 2
4 min read
Generic Class in Java
Java Generics was introduced to deal with type-safe objects. It makes the code stable.Java Generics methods and classes, enables programmer with a single method declaration, a set of related methods, a set of related types. Generics also provide compile-time type safety which allows programmers to catch invalid types at compile time. Generic means
4 min read
Generic Set In Java
The Set interface is present in java.util package. It is basically a collection of objects with no duplicate objects that means there can be no two objects in a Set e1 and e2 such that e1.equals(e2) and at most one null element. It is an interface that models the mathematical set. This interface inherits the features from the Collection interface a
3 min read
Generic Constructors and Interfaces in Java
Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “&lt;&gt;” after the class name as of the instance variable. Generic constructors are the same as generic methods. For generic constructors after th
5 min read
Generic Class Hierarchies in Java
Generic means parameterized types introduced in java5. These help in creating classes, interfaces, methods, etc. A class or method which works on parameterized type known as "generic class " or "generic method". Generics is a combination of language properties of the definition and use of Generic types and methods. Collections were used before Gene
3 min read
Generic MultiMap in java
In Java, a map is an interface. The map exists in the package java.util. The data is stored as a Key-Value pair in the map, which is a collection of keys and values. HashMap, TreeMap, and LinkedHashMap are the tools used to implement it. Every class has unique characteristics. It does not maintain the key order. What is MultiMap? Multiple identical
4 min read
Generic Servlet Class
GenericServlet implements the Servlet interface and provides an implementation for all its method except the service() method hence it is abstract. GenericServlet class defines a protocol-independent(HTTP-less) servlet. However, while building a website or an online application, we may want to have HTTP protocol, in that case, we must extend HttpSe
3 min read
Map Values() Method in Java With Examples
Map Values() method returns the Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. Syntax: map.values() Parameter: This method does not take any parameter. Return value: It returns a collection view of all the values present in the map. Exa
2 min read
IntStream map(IntUnaryOperator mapper) in Java
IntStream map(IntUnaryOperator mapper) returns a stream consisting of the results of applying the given function to the elements of this stream. This is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.
2 min read
Stream map() in Java with examples
Stream map(Function mapper) returns a stream consisting of the results of applying the given function to the elements of this stream. Stream map(Function mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance
3 min read
Immutable Map in Java
ImmutableMap, as suggested by the name, is a type of Map which is immutable. It means that the content of the map are fixed or constant after declaration, that is, they are read-only.If any attempt made to add, delete and update elements in the Map, UnsupportedOperationException is thrown.An ImmutableMap does not allow null element either.If any at
6 min read
EnumMap putAll(map) Method in Java
The Java.util.EnumMap.putAll(map) method in Java is used to copy all the mappings from one map to a newer one. Older mappings are replaced in a newer one. Syntax: void putAll(map) Parameters: The method takes one parameter map. It is the map which is to be copied to the newer one. Return Value The method does not return any value. Below programs il
2 min read
Program to Convert List to Map in Java
The List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes. The java.util.Map interface represents a mappi
5 min read
Replace null values with default value in Java Map
Given a Map with null values in it, the task is to replace all the null values with a default value. Examples: Input: map = {1=1, 2=2, 3=null, 4=4, 5=null, 6=null}, defaultValue = 0 Output: {1=1, 2=2, 3=0, 4=4, 5=0, 6=0} Input: map = {1=A, 2=B, 3=null, 4=D, 5=null, 6=null}, defaultValue = 'Z' Output: {1=A, 2=B, 3=Z, 4=D, 5=Z, 6=Z} Approach: Get the
3 min read
Flatten a Stream of Map in Java using forEach loop
Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]} Output: [G, e, e, k, s, F, o, r] Approach: Get the Map to be flattened. Create an empty list to c
3 min read
Map clear() method in Java with Example
The java.util.Map.clear() method in Java is used to clear and remove all of the elements or mappings from a specified Map collection. Syntax: void clear() Parameters: The method does not accept any parameters. Return Value: The method does not return any value. Below programs are used to illustrate the working of java.util.Map.clear() Method: Progr
2 min read
Map containsKey() method in Java with Examples
The java.util.Map.containsKey() method is used to check whether a particular key is being mapped into the Map or not. It takes the key element as a parameter and returns True if that element is mapped in the map. Syntax: boolean containsKey(key_element) Parameters: The method takes just one parameter key_element that refers to the key whose mapping
2 min read
Map containsValue() method in Java with Examples
The java.util.Map.containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the Map. It takes the value as a parameter and returns True if that value is mapped by any of the key in the map. Syntax: boolean containsValue(Object Value) Parameters: The method takes just one parameter Value o
2 min read
Map get() method in Java with Examples
The get() method of Map interface in Java is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key. So, let us check how to get value from the map in Java. Syntax of get() method in JavathisMap.get(Object key_element)Parameter and Return Value of
3 min read
Map entrySet() method in Java with Examples
The java.util.Map.entrySet() method in Java is used to create a set out of the same elements contained in the map. It basically returns a set view of the map or we can create a new set and store the map elements into them. Syntax: map.entrySet() Parameters: The method does not take any parameter. Return Value: The method returns a set having same e
2 min read
Map equals() method in Java with Examples
The java.util.Map.equals() method in Java is used to check for equality between two maps. It verifies whether the elements of one map passed as a parameter is equal to the elements of this map or not. Syntax: boolean equals(object obj) Parameters: The method accepts one parameter obj of this map type and refers to the map whose equality is to be ch
2 min read
Map putAll() Method in Java with Examples
This method is used to copy all of the mappings from the specified map to this map. Syntax: void putAll(Map m) Parameters: This method has the only argument map m, which contains key-value mappings to be copied to given map. Returns: This method returns previous value associated with the key if present, else return -1. Below programs show the imple
2 min read
Map isEmpty() Method in Java with Examples
This method is used to check if a map is having any entry for key and value pairs. If no mapping exists, then this returns true. Syntax: boolean isEmpty() Parameters: This method has no argument. Returns: This method returns True if the map does not contain any key-value mapping. Below programs show the implementation of int isEmpty() method. Progr
1 min read
Map keySet() Method in Java with Examples
This method is used to return a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. Syntax: Set keySet() Parameters: This method has no argument. Returns: This method returns a set containing keys of the specified map. Below programs show the implementation of int
2 min read
Map hashCode() Method in Java with Examples
This method is used to generate a hashCode for the given map containing key and values. Syntax: int hashCode() Parameters: This method has no argument. Returns: This method returns the hashCode value for the given map. Below programs show the implementation of int hashCode() method. Program 1: // Java code to show the implementation of // hashCode
1 min read
How to Clone a Map in Java
Given a map, the task is to clone that map. Following are the 5 different ways to Clone a Map in Java. Example: {1=Geeks, 2=For, 3=Geeks} Method 1: Naive method 1. Create an object for the class map. 2. Put the elements into the map using the put() method. 3. Again create another object for the class map. 4. Now finally iterate the map and call put
4 min read
Initialize a static map in Java with Examples
In this article, a static map is created and initialized in Java. A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Method 1: Creating a static map variable. Instantiating it in a static block. Below is the implementation of the above approach: // Java program to creat
1 min read
Initialize a static Map using Stream in Java
In this article, a static map is created and initialized in Java using Stream. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Stream In Java Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg