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
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
getKeymethod in which you can have map and valueToSearch as an arguments and using thestreamandfilterfunction , i have filtered the map based on the value andfindFirstwill give the desired output as shown in the code below.In your case, valueToSearch = newIndex.
Code:
TestCases: