Getting Key From HashMap Value

362 Views Asked by At

I have a HashMap for the alphabet that goes

HashMap<Character, Integer> alphabet = new HashMap<>();
   alphabet.put('A', 0);
   alphabet.put('B', 1);
   alphabet.put('C', 2);
   alphabet.put('D', 3);
   //And so on...

I'm trying to ket the key from the int value but am getting this error: The method getKey(int) is undefined for the type HashMap<Character,Integer>

Here's my code:

import java.util.Map.Entry; 
import java.util.HashMap; 
    
    String output = "";

   for(int i = 0; i < message.length(); i++){
        char letter = message.charAt(i);
        int n = alphabet.get(letter);
        int newIndex = Math.floorMod((n + k), 26);
        output += alphabet.getKey(newIndex);
   }
   System.out.println(output + "THE END");

I tried compiling it and got a "Cannot find symbol error" for the getKey function. Any idea what's causing this?

Thanks

1

There are 1 best solutions below

1
iamgirdhar On

Get Key from value in Map using Java 8 streams

As there is no pre-defined utility in Map to find the key from value, you can try the below approach for it.

Logic:

Here, I have created getKey method in which you can have map and valueToSearch as an arguments and using the stream and filter function , i have filtered the map based on the value and findFirst will give the desired output as shown in the code below.

In your case, valueToSearch = newIndex.

Code:

private static Character getKey(Map<Character, Integer> alphabet, 
                                int valueToSearch) {
    Character output = null;
    Optional<Character> optional =
            alphabet.entrySet().stream()
                    .filter(x -> x.getValue() == valueToSearch)
                    .map(Map.Entry::getKey).findFirst();
    if(optional.isPresent()){
        output = optional.get();
    }
    return output;
}

TestCases:

I/p: 3
O/p: D

I/p: 2
O/p: C