ADVERTISEMENT
ADVERTISEMENT

Java program to get the value based on the key from a HashMap collection

Given a HashMap collection, we have to get the value based on the key from it.
Submitted by Nidhi, on June 11, 2022

Problem Solution:

In this program, we will create a collection of key/value pair information using the HashMap collection. Then we will get values based on keys from HashMap using the get() method and print the result.

Program/Source Code:

The source code to get value based on the key from a HashMap collection is given below. The given program is compiled and executed successfully.

// Java program to get value based on the key 
// from a HashMap collection

import java.util.*;

public class Main {
  public static void main(String[] args) {
    HashMap < Integer, String > emp = new HashMap < > ();

    emp.put(101, "Amit");
    emp.put(102, "Arun");
    emp.put(103, "Akash");
    emp.put(104, "Ram");
    emp.put(105, "Mohan");

    System.out.println("Value for 101: " + emp.get(101));
    System.out.println("Value for 103: " + emp.get(103));
  }
}

Output:

Value for 101: Amit
Value for 103: Akash

Explanation:

In the above program, we imported the "java.util.*" package to use the HashMap class. Here, we created a public class Main.

The Main class contains a main() method. The main() method is the entry point for the program. And, created an object of the HashMap class and store the employee information using the put() method. Then we get values, based on keys from the HashMap collection using the get() method and printed the result.

Java HashMap Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.