Answers for "add keys and values to a map java"

26

java hashmap syntax

// Import the HashMap class
import java.util.HashMap;

	// First Example
    // Create a HashMap object called capitalCities
    HashMap<String, String> capitalCities = new HashMap<String, String>();

    // Add keys and values (Country, City)
    	capitalCities.put("England", "London");
    	capitalCities.put("Germany", "Berlin");
    	capitalCities.put("Norway", "Oslo");
    	capitalCities.put("USA", "Washington DC");
    	System.out.println(capitalCities);

	//Second Example
	// Create a HashMap object called stGrade
	Map<String, Integer> stGrade = new HashMap<String, Integer>(); 

	// Insert elements 
       	stGrade.put("aaron", new Integer(90)); 
       	stGrade.put("isaac", new Integer(100)); 
       	stGrade.put("john", new Integer(35)); 
       	stGrade.put("mohammad", new Integer(100)); 

	// Get value
	   	stGrade.get("mohammad"); 	// returns 100
		stGrade.get("aaron"); 		// returns 90
		stGrade.get("john");	 	// returns 35
		stGrade.get("isaac"); 		// returns 100
Posted by: Guest on June-08-2020
3

java add to map

HashMap<String, String> map = new HashMap<>();
map.put("key", "value");
Posted by: Guest on January-12-2021
0

access each key and value in a hashmap java

// access each key and corresponding value in a hashmap
HashMap<Integer, Integer> map = new HashMap<>();

for(Map.Entry<Integer, Integer> entry : map.entrySet()){
  entry.getKey();
  entry.getValue();
}
Posted by: Guest on December-03-2020

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language