user2982832
user2982832

Reputation: 177

every other letter in hashmap putting

HashMap<String,Integer> hm1 = new HashMap<String,Integer>
HashMap<String,Integer> hm2 = new HashMap<String,Integer>

I am looking to loop through an alphabet and add 'a-z' matching with numbers based on their occurrence in a text. I have this fully working however I am now changing this up. I want it to go through two hashmaps e.g. 'a' goes to hm1, 'b' goes to hm2, 'c' goes to hm1. 'd' goes to hm2. So every other one changes. I've been trying to do it for around a couple hours now and struggling.

I'm trying to do it by accessing the index of the value and trying to do modulo so if it's e.g. 0-25 then only doing then adding the even number index to one hashmap and the odd to the other. this way I would get every other letter as desired. However cannot seem to get this working, very frustrating!

EDIT: example:

  for ( char a = 'a'; a < z; a++){
    for ( int i = 0; 0<25; i++){
         h1.put(a,i);
          }
       }

if I wanted the above to do this but instead of all being in one hashmap, over two hashmaps so one doing a,c,e and the other doing b,d,f and so on... but with the values not being so obvious 0-25 but potentially large numbers.

Upvotes: 0

Views: 68

Answers (2)

Jaime A. Garc&#237;a
Jaime A. Garc&#237;a

Reputation: 155

You can get the first letter of of the key, get its int value (remember that in java, a character is a int value), and gets its modulo 2. Something like this:

private void putValue(String key, Integer value) {
      int firstLetterInt = (int) key.charAt(0);
      if (firstLetterInt % 2 == 0) {
          hm1.put(key, value);
      }
      else {
          hm2.put(key, value);
      }
 }

...

putValue("a", 66);
putValue("b", 100);

A more general case would be to have a list of Maps:

List<Map<String, Integer>> maps;

Providing the map is properly initialized, your putValue would look like:

private void putValue(String key, Integer value) {
      int firstLetterInt = (int) key.charAt(0);
      maps.get(firstLetterInt % maps.size()).put(key, value);
 }

Upvotes: 1

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299198

The double loop doesn't do what you think it does. For every value of a, you are executing the inner loop 25 times, which causes you to put every character as value 25. Instead of the inner loop, you should have a counter variable that is initialized outside the char loop and incremented inside it.

Upvotes: 1

Related Questions