Write a Java Program to Get key from HashMap using the value

Java Program to Get key from HashMap using the value

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Get key from HashMap using the value
Java Program to Get key from HashMap using the value

Write a Java Program to Get key from HashMap using the value

PROGRAM:Java Program to Get key from HashMap using the value

/*Java Program to Get key from HashMap using the value*/

import java.util.HashMap;
import java.util.Map.Entry;

class Main {
public static void main(String[] args) {

// create a hashmap
HashMap<String, Integer> numbers = new HashMap<>();
numbers.put(“One”, 1);
numbers.put(“Two”, 2);
numbers.put(“Three”, 3);
System.out.println(“HashMap: ” + numbers);

// value whose key is to be searched
Integer value = 3;

// iterate each entry of hashmap
for(Entry<String, Integer> entry: numbers.entrySet()) {

// if give value is equal to value from entry
// print the corresponding key
if(entry.getValue() == value) {
System.out.println(“The key for value ” + value + ” is ” + entry.getKey());
break;
}
}
}
}



Leave a Reply

Your email address will not be published. Required fields are marked *