将字符串与Map <character,string =“”>中的值进行比较并返回其键

时间:2018-11-16 18:23:45

标签: java hashmap iteration

大家好!

我有一张地图,键为字符,其值为字符串,它看起来如下(Baconian密码):

public class MyClass {

private static final Map<Character, String> cipheredAlphabet;
    static {
        cipheredAlphabet = new HashMap<Character, String>();
        cipheredAlphabet.put('a', "AAAAA");
        cipheredAlphabet.put('s', "BAABA");
    }
}

我有一个看起来像这样的字符串:

String encodedMessage = "BAABAAAAAA";

我想一次遍历5个字母进行遍历:

StringBuilder decodedMessage = new StringBuilder();
for(int i=0; i<encodedMessage.length(); i+=5) {
    String fiveLetters = encodedMessage.substring(i, i+5);
    // compare five letters to values and append the corresponding key

}

如何将这五个字母与地图中的值进行比较,并将对应的键附加到我的StringBuilder上?

预期输出:

sa

使用文档中的信息,我想到了这样的东西:

StringBuilder decodedMessage = new StringBuilder();
    for(int i=0; i<encodedMessage.length(); i+=5) {
        String fiveLetters = encodedMessage.substring(i, i+5);
        // pseudo code starts from this point
        for(Map.Entry<Character, String> entry: cipheredAlphabet.entrySet()) {
            if(cipheredAlphabet.getValue().equals(fiveLetters))
            decodedMessage.append(cipheredAlphabet.getKey());

1 个答案:

答案 0 :(得分:2)

for(Map.Entry<Character, String> entry: cipheredAlphabet.entrySet()) {
    if(entry.getValue().equals(fiveLetters)) {
        ecodedMessage.append(cipheredAlphabet.getKey());
        break;
    }
}

但是我认为最好在映射中交换键和值。

public class MyClass {

    private static final Map<String, Character> MAP = new HashMap<>();

    static {
        MAP.put("AAAAA", 'a');
        MAP.put("BAABA", 's');
    }

    public String decode(String msg) {
        if (msg == null || msg.length() % 5 != 0)
            throw new IllegalArgumentException("Message length should be a multiple of 5");

        StringBuilder buf = new StringBuilder();

        for (int i = 0; i < msg.length(); i += 5) {
            String letters = msg.substring(i, i + 5);
            Character ch = MAP.get(letters);

            if (ch == null)
                throw new IllegalArgumentException("Letters '" + letters + "' not found in local map");

            buf.append(ch);
        }

        return buf.toString();
    }
}