In: Computer Science
Let's get some practice with maps! Create a public class CountLetters providing a single static method countLetters. countLetters accepts an array of Strings and returns a Map from Strings to Integers. (You can reject null arguments using assert.) The map should contain counts of the passed Strings based on their first letter. For example, provided the array {"test", "me", "testing"} your Map should be {"t": 2, "m": 1}. You should ignore empty Strings and not include any zero counts. As a reminder, you can retrieve the first character of a String as a char using charAt. You may find substring more helpful. You may also want to examine the Map getOrDefault method. You can use any Map implementation in java.util.
import java.util.HashMap;
import java.util.Map;
public class CountLetters {
public static void main(String[] args) {
String str[]= {"test", "me", "testing"};
System.out.println(countLetters (str));
}
public static Map<String, Integer> countLetters (String[] str) {
Map<String, Integer> map = new HashMap<String, Integer>();
//Iterating thorugh the given array of strings
for (String s : str) {
//checking if string is empty than not processing
if (s==null || s.trim().length() == 0)
continue;
//extracting the first char
String firstChar = s.substring(0, 1);
//checking if first char is already in the map
// than get that value of give 0
int count = map.getOrDefault(firstChar, 0);
//increasing it by 1 and putting
map.put(firstChar, count + 1);
}
return map;
}
}
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
I AM HERE TO HELP YOUIF YOU LIKE MY ANSWER PLEASE RATE AND HELP ME IT IS VERY IMP FOR ME