×

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We can store the items or values using a hash map, and we can access those values using indexes or keys of any type, including Integer, String, Double, Character, and user-defined datatypes.

A HashMap uses Key -> Value as the source of its mappings.

Since Java 1.2, HashMap has been a component of Java. It uses the Java.util API. The map interface.

What is the definition of Generic Map and what does it differ from HashMap?

The notion behind the term "generic" is simply that any user-defined type, such as an integer, double, string, or another, may be used as a parameter for methods, classes, or interfaces. For instance, generics are used by all of Java's built-in collections, including ArrayList, HashSet, HashMap, etc.

Generic Map can be summed up as follows in basic English:

Map< K, V > map = new HashMap< K, V >();

Where generic type parameter given with in declaration of a HashMap is specified by K and V. In the following syntax, K and V can be replaced with any type, such as an Integer, String, Float, Character, or any user-defined type, to indicate that we can populate the HashMap as we choose.

Example :

We can initialize it as follows if key is of type String as well as the matching value seems to be of type Integer:

Map< String , Integer > map = new HashMap< String ,Integer >();

Only String instances can now be used as keys and Integer instances can be used as values in the map.

A Generic Map Can Be accessed:

The functions put() and get() can be used to accomplish this.

  1. put(): used to update the HashMap with a new key/value pair.
  2. get(): used to obtain the value associated with a specific key.

Example:

Map< Integer, String > map = new HashMap<>();
// 123 and the value are added.
// corresponding to it on the map as abc
map.put( 123, "abc");     
map.put(65, "b");
map.put(2554 , "Generic");
map.get(65);

Output:

b

Iterating A generic map:

For iteration, the map has two collections. KeySet() and values are two examples.

Example:

By using iterator() method
Map<Integer, Integer> map = new HashMap<>;
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:

utilizing a fresh for-loop, a for-each loop, or a generic for loop

//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 demonstrate how to use a map:

  import java.io.*;
import java.util.*;
  
class GenericMap {
  
    public static void main(String[] args)
    {
        // To create array of strings
        String arr[]
            = { "generic",  "code",    "map",   "program",
                "code", "site", "map",   "generic",
                "java", "generic",     "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);
            }
        }
       
        System.out.println(map.get("generic"));
        System.out.println(map.get("code"));
    }
}

Output :

3
2

Using Java Generics, Map Different Value Types:

Let's say for the purpose of illustration that you need to offer some sort of application environment that enables you to bind data of any type to certain keys. An easy non-type safe implementation with String keys and a HashMap backing might appear as follows:

public class Scope {
  private final Map<String,Object> values = new HashMap<>();
  public void put( String key, Object value ) {
    values.put( key, value );
  }
  public Object get( String key ) {
    return values.get( key );
  }
  [...]
}

How to use this Scope in a program is demonstrated by the following snippet:

Scope scope = new Scope();
Runnable runnable = . . .
Scope.put( “key” , runnable);
// iterations of computations late
Runnable value = ( Runnable )scope.get( “key” );

This is the scope of a program to demonstrate’s the following snippet.


Related Topics

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

How to compare dates in Java

Introduction: In Java, dates can be compared using a similar interface's compareTo() technique. This method returns 'zero' if each date is the same, returns a rate "more than 0" if...

6 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

Catalan number in Java

In general mathematics, Catalan numbers can be defined as the sequence of natural numbers that frequently occur in counting problems often encountered in recursively defined objects. Mathematical formula of Catalan number Coming...

3 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.