Java Collection Tutorial - Java HashMap.put(K key, V value)








Syntax

HashMap.put(K key, V value) has the following syntax.

public V put(K key, V value)

Example

In the following code shows how to use HashMap.put(K key, V value) method.

/*from   www .ja v a 2 s .  com*/

import java.util.HashMap;

public class Main {
   public static void main(String args[]) {
      HashMap<Integer, String> newmap = new HashMap<Integer, String>();      
      
      // populate hash map
      newmap.put(1, "tutorials");
      newmap.put(2, "from");
      newmap.put(3, "java2s.com");
      
      System.out.println("Map value before change: "+ newmap);
      
      // put new values at key 3
      String prevvalue=(String)newmap.put(3,"is great");
      
      // check returned previous value
      System.out.println("Returned previous value: "+ prevvalue);
      
      System.out.println("Map value after change: "+ newmap);
   }    
}

The code above generates the following result.