×

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

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 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.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 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.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Java Math floor() Method

The floor() method of Math class returns the largest double value that is equal to a mathematical integer and is less than or equal to the argument. Syntax: public static double floor(double...

2 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute 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 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string...

4 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.