In: Computer Science
Language: JavaScript
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.
Below is currently what I've done.
import java.util.Map;
import java.util.HashMap;
public class CountLetters {
public static countletters(String[] data) {
assert(data != null);
}
}
In case of any query do comment. Please rate answer as well. Thanks
Code:
import java.util.HashMap;
public class Countletters
{
public static void main (String[]args)
{
String[] data = {"test", "me", "testing"};
HashMap<String,Integer> letterCountMap = countletters(data);
System.out.println(letterCountMap);
}
//count leter method which will return Map string to intgers which will count of starting letter to count
public static HashMap <String,Integer> countletters (String[]data)
{
assert (data != null);
HashMap <String,Integer> letterCountMap =
new HashMap <String,Integer> ();
for (int i = 0; i < data.length; i++)
{
if (data[i] != null && !data[i].isEmpty ())
{
String str = data[i].substring (0,1);
if (letterCountMap.containsKey (str))
{
//if String is already in the map then increase the count by 1
int count = letterCountMap.get (str) + 1;
letterCountMap.put (str, count);
}
else
{
// if String is not present then add it with count 1
letterCountMap.put (str, 1);
}
}
}
//return the map
return letterCountMap;
}
}
=========Output and screen shot of the code=====