0

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Alpenkuh1
  • 3
  • 1
  • What have you tried? Why can't you just put a new value for the key? – Erwin Bolwidt Jan 17 '21 at 12:35
  • You can't update keys of a map. Simply you can delete the existing one and add a new value into map with the new key. https://stackoverflow.com/questions/10766906/is-it-possible-to-rename-a-hashmap-key/10766924#:~:text=You%20cannot%20rename%2Fmodify%20the,key%20modifier%20marked%20as%20final%20.&text=You%20don't%20rename%20a,and%20delete%20the%20old%20one. – Harshana Jan 17 '21 at 12:39
  • @Harshana this is not about updating keys, but updating the value of an existing key – f1sh Jan 17 '21 at 13:05

1 Answers1

1

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}
f1sh
  • 11,489
  • 3
  • 25
  • 51
  • 1
    You beat me to it... my attempt looked exactly the same but with an additional check to make sure `kvsplit` has length 2. – Matt Jan 17 '21 at 12:44
  • Yes, my attempt obviously omits all the checks that you would usually do. But it works with the given example input, so... :D – f1sh Jan 17 '21 at 12:48