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;
}   
\$\endgroup\$
  • 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 Aug 9 '19 at 9:39
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)

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Wow, that is great. So to the point. \$\endgroup\$ – John O Sullivan Aug 2 '19 at 10:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.