×

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

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Classes and Objects in Java Example Programs

Classes and Objects in Java Example Programs Java is an Object-Oriented programming language, i.e., everything in Java is associated with objects and objects are associated with classes. The classes and objects...

5 minutes read.

CopyOnWriteArrayList in Java

The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating...

5 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.