In: Computer Science
For Java
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.
Program Code Screenshot
Sample Output
Program Code to Copy
import java.util.HashMap; import java.util.Map; class CountLetters{ static Map countLetters(String str[]){ //Create a new map Map<String,Integer> map = new HashMap(); //Loop through all strings in the array for(String s : str){ //add to map map.put(s.substring(0,1),map.getOrDefault(s.substring(0,1),0)+1); } return map; } public static void main(String[] args) { Map<String,Integer> map = countLetters(new String[]{"test","me","testing"}); System.out.println(map); } }