Write A Java Program To Create A New Hashmap, Add 5 Students’ Data (Enrolment No And Name). Retrieve And Display The Student’s Name From Hashmap Using Enrolment No
Before demonstrate the program we will understand the concept of Hashmap.
HashMap in Java is a class that implements the Map interface and provides a way to store and retrieve key-value pairs. It allows you to store and access elements based on the key rather than their index or position.
In a HashMap, keys are unique and are used to retrieve the corresponding value. The HashMap class uses an array and a linked list data structure to store the key-value pairs. Each key-value pair is stored in a Map.Entry object, which is then stored in the array.
The HashMap class provides several methods to manipulate the key-value pairs, such as put(key, value), get(key), remove(key), and containsKey(key).
Program
import java.util.HashMap;
public class StudentHashMap { public static void main(String[] args) { // Create a new HashMap to store student data HashMap<Integer, String> students = new HashMap<>();
// Add 5 students' data to the HashMap students.put(1001, "Harsh"); students.put(1002, "Tirth"); students.put(1003, "Jayraj"); students.put(1004, "Sahejan"); students.put(1005, "Vedant");
// Display a student's name using their enrollment number int enrollmentNumber = 1003; String studentName = students.get(enrollmentNumber); System.out.println("Student with enrollment number " + enrollmentNumber + ": " + studentName); }}
Output
Student with enrollment number 1003: Jayraj
In this program, we first create a new HashMap called studentDetails to store the student details. We then add 5 students' details to the HashMap using the put() method. Each student's enrolment number is used as the key and their name is used as the value.
Next, we retrieve the student's name using their enrolment number (1003) from the HashMap using the get() method and store it in the studentName variable. Finally, we print out the student's name along with their enrolment number to the console.
❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In Java Programming.