Home > Blockchain >  How to print the key of hashmap using value
How to print the key of hashmap using value

Time:04-10

I can print the value using key, but I can't able to print the key using its value.

Source code

   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();
      }
    }

Program Output

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

CodePudding user response:

For example, you want to find key using value 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);
  • Related