Issue
I am not able to get the correct occurrence of each letter present in the string. What is wrong with my code?
Code:
public class consecutiveCharacters {
public static String solve(String A, int B) {
HashMap<String, Integer> map = new HashMap<>();
for (int i=0;i<A.length();i++) {
Integer value = map.get(A.charAt(i));
if(value == null){
map.put(String.valueOf(A.charAt(i)),1);
}
else {
map.put(String.valueOf(A.charAt(i)),i+1);
}
}
System.out.println(map);
String text = "i feel good";
return text;
}
public static void main(String[] args) {
solve("aabbccd",2);
}
}
The output of the map should be:
{a=2, b=2, c=2, d=1}
Yet the output that the above code is giving is:
{a=1, b=1, c=1, d=1}
Solution
Using Map.merge()
you can rid of checking this yourself:
Map<Character, Integer> map = new HashMap<>();
for( char c : A.toCharArray()) {
map.merge(c, 1, Integer::sum);
}
merge()
takes 3 parameters:
- A key which is the character in your case
- A value to put for the key, which is 1 in your case
- A merge bi-function to combine the new and existing values if the entry already existed.
Integer::sum
refers toInteger's
methodstatic int sum(int a, int b)
which basically is the same as yourvalue + 1
.
Answered By - Thomas