使用值获取 HashMap 中键的 Java 程序
在本文中,我们将了解如何使用值来获取 HashMap 中的键。Java HashMap 是 Java 的 Map 接口的散列表实现。它是一组键值对。
以下是对它的演示 −
假设我们的输入是 −
Input HashMap: {Java=8, Scala=5, Python=15}
Key: 8期望的输出将是 −
The value of Key: 8 is Java
算法
Step 1 - START Step 2 - Declare namely Step 3 - Define the values. Step 4 - Create a HashMap of integer and string values and initialize elements in it using the ‘put’ method. Step 5 - Define a key value. Step 6 - Iterate over the elements of HashMap, and check if the key previously defined is present in the HashMap. Step 7 - If found, break away from the loop. Step 8 - Display the result Step 9 - Stop
示例 1
在这里,我们在“main”函数下将所有操作绑定在一起。
import java.util.HashMap;
import java.util.Map.Entry;
public class Demo {
public static void main(String[] args) {
System.out.println("The required packages have been imported");
HashMap<String, Integer> input_map = new HashMap<>();
input_map.put("Scala", 5);
input_map.put("Java", 8);
input_map.put("Python", 15);
System.out.println("The HashMap is defined as: " + input_map);
Integer Key = 8;
for(Entry<String, Integer> entry: input_map.entrySet()) {
if(entry.getValue() == Key) {
System.out.println("\nThe value of Key: " + Key + " is " + entry.getKey());
break;
}
}
}
}输出
The required packages have been imported
The HashMap is defined as: {Java=8, Scala=5, Python=15}
The value of Key: 8 is Java示例 2
在这里,我们将操作封装到函数中,展示了面向对象编程。
import java.util.HashMap;
import java.util.Map.Entry;
public class Demo {
static void get_value(HashMap<String, Integer> input_map,Integer Key){
for(Entry<String, Integer> entry: input_map.entrySet()) {
if(entry.getValue() == Key) {
System.out.println("\nThe value of Key: " + Key + " is " + entry.getKey());
break;
}
}
}
public static void main(String[] args) {
System.out.println("The required packages have been imported");
HashMap<String, Integer> input_map = new HashMap<>();
input_map.put("Scala", 5);
input_map.put("Java", 8);
input_map.put("Python", 15);
System.out.println("The HashMap is defined as: " + input_map);
Integer Key = 8;
get_value(input_map, Key);
}
}输出
The required packages have been imported
The HashMap is defined as: {Java=8, Scala=5, Python=15}
The value of Key: 8 is Java
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP