Example using Map in Java


The Map Interface in Java just like dictionaries in Python. It have function to create key – value data structure which each key must be unique. In Java term, this data structure create association between one object to another object.

This is how to use Map() interface in Java:

Filename: MapExample.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// I need to import Map and HashMap interface
import java.util.HashMap;
import java.util.Map;

// I create public class to make class loader find implementation for this files
public class MapExample {
    public static void main(String[] args) {

        // I create new params variable with mapping Integer, String objects associated as key-value
        Map<Integer, String> params = new HashMap<Integer, String>();
     
        // I create a new key-value {1: "Hello World}
        params.put(1, "Hello World");

        // I print params data structure and it’s value
        System.out.println(params);
    }  
}

When we execute the code, it will return:

1
{1=Hello World}

We can store objects inside Map() Interface.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.