Search code examples
javatreemap

How can I add an associated value to a map that already has a key?


I have a Map<Character, String> that already gets a value for the key (Character) based on a for loop. How can I now go through this map and check whether a certain key is in this map (e.g. 'A' or 'a' [because case ignore]) and then add my desired value (e.g. 4) to this key (so that from "A=" becomes an "A=4")?

I hope my problem is clear

Here is my present code:

public static Map<Character, String> replacings(String s) {
    Map<Character, String> leetMap = new TreeMap<>();
    for(int i = 1; i < s.length(); i++) {
        if(s.charAt(i) == '=') {
            leetMap.put(s.charAt(i - 1), "");
            leetMap.put(s.toLowerCase().charAt(i - 1), "");
        }
    }
    for(int j = 0; j < leetMap.size(); j++) {
        //look for the key here and then add a value to it [my problem]
    }
    return leetMap;
}

My main method until yet (example):

Map<Character, String> mappings = replacings(
    "A=4,B=8,E=3,G=6,L=1,O=0,S=5,T=7,Z=2,"
);

So now, I want to add the numbers to the keys.


Solution

  • You can iterate over a map using it's entrySet like this:

    for(Map.Entry<Character, String> entry : leetMap.entrySet()) {
       if(e.getKey() == 'A') {
         //things
       }
    }
    

    But the real question is why you want this to happen in different loops? Why are you not adding the value to the map at the same time when you add the key?

    My attempt looks like this:

    private static Map<Character, String> replacings(String s) {
      Map<Character, String> leetMap = new TreeMap<>();
      String[] splitted = s.split(",");
      for (String kv : splitted) {
        String[] kvsplit = kv.split("=");
        leetMap.put(kvsplit[0].charAt(0), kvsplit[1]);
        leetMap.put(kvsplit[0].toLowerCase().charAt(0), kvsplit[1]);
      }
      return leetMap;
    }
    

    this prints:

    {A=4, B=8, E=3, G=6, L=1, O=0, S=5, T=7, Z=2, a=4, b=8, e=3, g=6, l=1, o=0, s=5, t=7, z=2}