Given an array of non-empty strings, return a Map<String, String> with a key for every different first character seen, with the value of all the strings starting with that character appended together in the order they appear in the array.
firstChar(["salt", "tea", "soda", "toast"]) → {"t": "teatoast", "s": "saltsoda"}
firstChar(["aa", "bb", "cc", "aAA", "cCC", "d"]) → {"d": "d", "b": "bb", "c": "cccCC", "a": "aaaAA"}
firstChar([]) → {}
Given an array of non-empty strings, return a Map<String, String> with a key for every different first character seen, with the value of all the strings starting with that character appended together in the order they appear in the array.
firstChar(["salt", "tea", "soda", "toast"]) → {"t": "teatoast", "s": "saltsoda"}
every different first
public Map < String, String > firstChar(String[] strings) {
Map < String, String > map = new HashMap < String, String > ();
for (int i = 0; i < strings.length; i++) {
String k = String.valueOf(strings[i].charAt(0));
if (map.containsKey(k)) {
String val = map.get(k) + strings[i];
map.put(k, val);
} else {
map.put(k, strings[i]);
}
}
return map;
}
public Map<String, String> firstChar(String[] strings) {
Map<String, String> map = new HashMap();
// for (int i = 0; i < strings.length; i++) {
for(String str:strings)
String k = String.valueOf(str.charAt(0));
if (map.containsKey(k)) {
String val = map.get(k) + strings[i];
map.put(k, val);
} else {
map.put(k, strings[i]);
}
}
return map;
}
Compile problems:
Error: String k = String.valueOf(str.charAt(0));
^^^^^^
Syntax error, insert "AssignmentOperator ArrayInitializer" to complete ArrayInitializerAssignement
see Example Code to help with compile problems
public Map<String, String> firstChar(String[] strings) {
Map<String, String> map = new HashMap();
// for (int i = 0; i < strings.length; i++) {
for(String str:strings){
String k = String.valueOf(str.charAt(0));
if (map.containsKey(k)) {
String val = map.get(k) + str;
map.put(k, val);
} else {
map.put(k, str);
}
}
return map;
}
i corrected it. missed { and also used strings[i] at one place
// String val = map.get(k) + str;
map.put(k, map.get(k) + str);
> "i was not clear on above description. please advise"
Unless you tell us which parts of the description you are not clear on, it's a bit hard for us to know how to advise you. Do you expect us to rewrite the entire description and hope that you understand our version?
So, instead of making this a guessing game for us, please be specific. We're expert programmers, not expert mind readers.
Thanks.
tel2