Follow-up: Find sum of number of times that each character of source occurs in the target This question is a follow-up of this question. The aim of the questions is to find sum of number of times that each character of source occurs in the target.

In the new code, I've renamed the char array and added the functionality to prevent the following "if a character is duplicated in the source, you will double-count it in the result."

I would like to know if there is still a better solution for it.

It was mentioned in one of the answers of the previous question that I should use HashMap or other data structures for chars more than 100, but I am not sure how and why.

String target = "alex alexander";
String source = "ardx"; 
Map&lt;Character,Integer&gt; tempMap = new HashMap&lt;&gt;();

char[] tchars = source.toCharArray();

int occur = 0;
int occurrence = 0;

for (int i = 0; i &lt; tchars.length; i++) {
   if(!tempMap.containsKey(tchars[i])){ //if the occurrence of the current char 
        String temp = target;           //   has been already calculated  
        int index = temp.indexOf(tchars[i]);

        while (index != -1) {
            occur++;
            index = temp.indexOf(tchars[i], index + 1);
        }
        tempMap.put(tchars[i],occur);
        occurrence += occur; //add to the total counter
        occur = 0;           //reset the single counter
   }else{
       occurrence += tempMap.get(tchars[i]);
   }

}
System.out.println(occurrence);


Output


a is added to the map and its associated counter is 3
r is added to the map and its associated counter is 1
d is added to the map and its associated counter is 1
x is added to the map and its associated counter is 2
25
Sorry, but this looks worse. I guess, you've been confused by the different ideas presented in the answers. And I am, confused, too. I don't understand it, so just some minor comments:

//reset the single counter


This is a sign that you've defined the counter in a wrong scope. Define it inside of the loop.



tempMap, temp... everything is temporary, we too. But this doesn't mean that it can't be properly named. Or removed... you need no temp String anymore.



I think I sort of understand it. The tempMap keeps track of the number of occurrences per character. So name it like it....

I don't think it really works. However, why not use a Set to keep track of what chars you've seen already? The logic is then trivial: "already seen -> skip it".

Enough for now.