1676473843887 - Write a program using a hashmap to add and retrieve data and print it in the console.

Write a program using a hashmap to add and retrieve data and print it in the console.
Write a program using a hashmap to add and retrieve data and print it in the console.




Here is an example program in Java that uses a HashMap to add and retrieve data, and print it in the console:

import java.util.HashMap;

public class HashMapExample {
public static void main(String[] args) {
// create a new HashMap to store data
HashMap<Integer, String> map = new HashMap<Integer, String>();

// add data to the HashMap
map.put(1, "John");
map.put(2, "Jane");
map.put(3, "Bob");
map.put(4, "Alice");

// retrieve data from the HashMap and print it in the console
System.out.println("Data in the HashMap:");
System.out.println("Key: 1, Value: " + map.get(1));
System.out.println("Key: 2, Value: " + map.get(2));
System.out.println("Key: 3, Value: " + map.get(3));
System.out.println("Key: 4, Value: " + map.get(4));
}
}

In this example, we create a new HashMap to store data, with integer keys and string values. We then add some data to the HashMap using the put() method. We then retrieve the data from the HashMap using the get() method and print it in the console.

The output of this program will be:

Data in the HashMap:
Key: 1, Value: John
Key: 2, Value: Jane
Key: 3, Value: Bob
Key: 4, Value: Alice

This shows that we were able to successfully add data to the HashMap and retrieve it using the keys. We then printed the data in the console using the println() method.

In summary, HashMap can be used to store data in key-value pairs, and can be useful when we want to store data for later use. This example program demonstrates how to use a HashMap to add and retrieve data, and print it in the console.









Pages