-1

I have a hash map that contains the following mappings ....

    HashMap <String , Integer>hm  = new HashMap <String , Integer> (); 
    hm.put("e", 0);
    hm.put("h",1);
    hm.put("i", 2);
    hm.put("k",3);
    hm.put("l",4);
    hm.put("r",5);
    hm.put("s",6);
    hm.put("t",7);

Along with this i have a binary sequence , which i have obtained from another computation as

 1 0 10 100 1 10 111 100 0 101 

My objective is to get the resultant characters that these binary digits display from the hash map above .

For example .... 001 = 1 = h 
                 000 = 0 = e
                 010 = 2 = i

This code is part of a program that implements the one time pad in cryptography . I have performed the encryption as well as the decryption .

refer answer 3 here for the proof of code :

storing charcter and binary number in a hash map

But am struggling to display the decrypted binary code output , to the letters in my hash map .

Thanks in advance

Community
  • 1
  • 1

2 Answers2

0

You need to map from the value to the key (which is the reverse of the way a HashMap works). Build a decryption Map.

Map<Integer, String> dec = new HashMap<>();
for (Map.Entry<String, Integer> kp : hm.entrySet()) {
    dec.put(kp.getValue(), kp.getKey());
}

Then you can iterate that by parsing your input values to int and getting the corresponding value. Like

String input = "1 0 10 100 1 10 111 100 0 101";
Stream.of(input.split("\\s+")).map(s -> dec.get(Integer.parseInt(s, 2)))
        .forEachOrdered(s -> System.out.print(s + " "));
System.out.println();
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Make a new map with the values and the rows swapped.

final Map<String, Integer> hm = ...
final Map<Integer, String> mapping = hm.entrySet().stream()
    .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));

Now you can use this map to do your lookup:

final List<Byte> bytes = ...
final List<String> keys = bytes.stream()
    .map(mapping::get)
    .collect(Collectors.toList());
flakes
  • 21,558
  • 8
  • 41
  • 88