Java 程序使用值从 HashMap 获取键

javacampus interviewserver side programmingprogramming

在本文中,我们将了解如何使用值从 HashMap 获取键。Java HashMap 是基于哈希表的 Java Map 接口实现。它是键值对的集合。

下面是相同的演示 −

假设我们的输入是

输入 HashMap:{Java=8, Scala=5, Python=15}
Key:8

期望输出将是

Key:8 的值是 Java

算法

步骤 1 - 开始
步骤 2 - 声明
步骤 3 - 定义值。
步骤 4 - 创建整数和字符串值的 HashMap,并使用‘put’方法初始化其中的元素。
步骤 5 - 定义键值。
步骤 6 - 遍历 HashMap 的元素,并检查先前定义的键是否存在于 HashMap 中。
步骤 7 - 如果找到,则退出循环。
步骤 8 - 显示结果
步骤 9 - 停止

示例 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

相关文章