如何使用值打印哈希图的键

How to print the key of hashmap using value

我可以使用键打印值,但我无法使用它的值打印键。

源代码

   public class test {
      public static void main(String[] args) {
        Map<Integer, String> hashMap = new HashMap<>();
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number of element to insert in map:");
        int num = sc.nextInt();
        sc.nextLine();
        for (int i = 0; i < num; i++) {
          System.out.print("Enter a Key:");
          int num1 = sc.nextInt();
          sc.nextLine();
          System.out.print("Enter a value:");
          String str1 = sc.nextLine();
          hashMap.put(num1, str1);
        }
        System.out.println(hashMap);
        System.out.println(hashMap.get(1));
        sc.close();
      }
    }

程序输出

Enter a number of element to insert in map:2
Enter a Key:1
Enter a value:a
Enter a Key:2
Enter a value:b
{1=a, 2=b}
a

例如,您要使用值 abc 查找键:

String res;
HashMap<String, String> hashMap = new HashMap<>();
Set<Map.Entry<String, String>> entrySet = hashMap.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
  if (entry.getValue().equals("abc")) {
    res = entry.getKey();
    break;
  }
}
System.out.println(res);