w3resource

Java: Associate the specified value with the specified key in a HashMap


1. Associate Key with Value in HashMap

Write a Java program to associate the specified value with the specified key in a HashMap.

Sample Solution:

Java Code:

import java.util.*;  
public class Example1 {  
  public static void main(String args[]) {  
  HashMap<Integer,String> hash_map= new HashMap<Integer,String>();  
  hash_map.put(1, "Red");
  hash_map.put(2, "Green");
  hash_map.put(3, "Black");
  hash_map.put(4, "White");
  hash_map.put(5, "Blue");
  for(Map.Entry x:hash_map.entrySet()){  
   System.out.println(x.getKey()+" "+x.getValue());  
  }  
 }  
}

Sample Output:

1 Red                                                                  
2 Green                                                                
3 Black                                                                
4 White                                                                
5 Blue

For more Practice: Solve these Related Problems:

  • Write a Java program to insert a key-value pair into a HashMap and then update the value if the key already exists.
  • Write a Java program to merge two HashMaps such that if keys collide, the values are concatenated into a single string.
  • Write a Java program to create a HashMap, add key-value pairs, and then remove a key only if it is mapped to a specific value.
  • Write a Java program to implement a method that adds a key-value pair to a HashMap and returns the previous value associated with the key.

Go to:


PREV : Java HashMap Exercises Home.
NEXT : Count Key-Value Mappings in Map.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.