\$\begingroup\$
\$\endgroup\$
1
Is it possible to write this using the stream element? I can get the most of it with stream but it is the add adding string to list which is in the map that I am caught on.
/**
* Given a list of strings, returns a map where the keys are the unique strings lengths found in the list and the values are the strings matching each length
* [hello,world,cat,ambulance] would return {5 -> [hello, world], 3 -> [cat] -> 3, 9 -> [ambulance]}
* @param strings
* @return
*/
public Map<Integer,List<String>> mapLengthToMatchingStrings(List<String> strings){
Map<Integer,List<String>> mapILS = new HashMap<Integer, List<String>>();
for (String str : strings) {
int length = str.length();
if (mapILS.containsKey(length)) {
// Add str to list at key
//Get list at key
List<String> rs = mapILS.get(length);
//Add str to list
rs.add(str);
//Update key in map
mapILS.put(length, rs);
}else {
// Add new key list to map
//Create list
List<String> rs = new ArrayList<String>();
//Add string
rs.add(str);
//Add key and list to map
mapILS.put(length, rs);
}
}
return mapILS;
}
asked Aug 2, 2019 at 9:00
-
1\$\begingroup\$ For anyone voting to close this question: yes, it could be worded better. But the code seems to work and there's a description in the title & comments. The specific request is usually off-topic, but it would've been the likely outcome in a review anyway. John, for your next question, please read our FAQ on asking questions. \$\endgroup\$Mast– Mast ♦2019年08月09日 09:39:59 +00:00Commented Aug 9, 2019 at 9:39
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
It's not only possible but also a great example of how functional programming can make code much simpler and readable:
public Map<Integer,List<String>> mapLengthToMatchingStrings(List<String> strings){
return strings.stream().distinct().collect(Collectors.groupingBy(String::length));
}
(The distinct
part is optional, regarding whether you want duplicates in the lists)
answered Aug 2, 2019 at 9:50
-
\$\begingroup\$ Wow, that is great. So to the point. \$\endgroup\$John O Sullivan– John O Sullivan2019年08月02日 10:43:56 +00:00Commented Aug 2, 2019 at 10:43
lang-java