Java Online Compiler
Example: HashMapExample in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// HashMapExample import java.util.HashMap; import java.util.Map; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create a HashMap to store String (key) and Integer (value) pairs Map<String, Integer> studentScores = new HashMap<>(); System.out.println("Initial student scores: " + studentScores); // Step 2: Add key-value pairs to the HashMap studentScores.put("Alice", 95); studentScores.put("Bob", 88); studentScores.put("Charlie", 92); System.out.println("After adding scores: " + studentScores); // Step 3: Retrieve a value using its key int aliceScore = studentScores.get("Alice"); System.out.println("Alice's score: " + aliceScore); // Step 4: Check if a key or value exists boolean hasBob = studentScores.containsKey("Bob"); boolean hasScore90 = studentScores.containsValue(90); System.out.println("Contains Bob? " + hasBob); System.out.println("Contains score 90? " + hasScore90); // Step 5: Update a value studentScores.put("Bob", 90); // Overwrites Bob's previous score System.out.println("After updating Bob's score: " + studentScores); // Step 6: Remove a key-value pair studentScores.remove("Charlie"); System.out.println("After removing Charlie: " + studentScores); // Step 7: Iterate through key-value pairs System.out.println("All scores:"); for (Map.Entry<String, Integer> entry : studentScores.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } }
Output
Clear
ADVERTISEMENTS