Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Insert in Map


How to insert a new Item in a Map using put() method?


Let us say, we have a Map that should contain,


John, Is a Name
Java, Is a Language

As Key and Value pair.


Let us insert above values to the Map in the below example.


Example :



import java.util.*;

public class MyApplication {
    public static void main(String[] args) {

        Map x = new HashMap<>();

        x.put("John", "Is a Name");
        x.put("Java", "Is a Language");

        System.out.println(x);
    }
}


Output :



  {Java=Is a Language, John=Is a Name}

So, in the above code we have created a Map,


Map x = new HashMap<>();

And used the put() method to insert values to it.


x.put("John", "Is a Name");
x.put("Java", "Is a Language");

Below is the way how the values are placed in the Map as Key value pairs. Where John is the Key and Is a Name is the value.

Spring_Boot

Duplicate Keys are not allowed in Map


So, we have a Map that contains,


John, Is a Name
Java, Is a Language

As Key and Value pair.


Now, let us say, we want to insert a new entry,


John, Is an English Name

Where John is the Key and Is an English Name is its corresponding Value.


Let us see in the below example.


Example :



import java.util.*;

public class MyApplication {
    public static void main(String[] args) {

        Map x = new HashMap<>();

        x.put("John", "Is a Name");
        x.put("Java", "Is a Language");

        x.put("John", "Is an English Name");

        System.out.println(x);
    }
}


Output :



  {Java=Is a Language, John=Is an English Name}

So, for the Key John, the initial value was Is a Name.


x.put("John", "Is a Name");

And we wanted to add a new entry with the Key as John and the Value as Is an English Name.


x.put("John", "Is an English Name");

But if we see the output.