2
\$\begingroup\$

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;
} 
Mast
13.8k12 gold badges56 silver badges127 bronze badges
asked Aug 2, 2019 at 9:00
\$\endgroup\$
1
  • 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\$ Commented Aug 9, 2019 at 9:39

1 Answer 1

2
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Wow, that is great. So to the point. \$\endgroup\$ Commented Aug 2, 2019 at 10:43

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.