Q:

Java Stream issue

I'm training using streams in java. 
That's the request:
returns list of strings
     containing the name of the doctor and the relative number of patients
     sorted by decreasing number.
     The string must be formatted as "### : ID SURNAME NAME" where ###
     represent the number of patients (printed on three characters). 
public Collection<String> doctorsByNumPatients(){
        SortedMap<Integer, List<String>> a= doctors.values().stream().
                collect(groupingBy(d->d.getPatients().size(), ()->new TreeMap<Integer, List<String>>(reverseOrder()), mapping(Doctor::toString, toList())));

        return a.entrySet().stream().
                ??????????
    }

(Doctor::toString returns ID NAME SURNAME)
I wrote this code but i can't finish it cause i don't know how to turn the map into the string's list as suggested in the request, using stream. I solved a similar problem but dealing the map with a loop in which for each iteration I initialized an iterator to scan the value (list) and generate a string for each doctor in any list. 

A:

Nice try.
I suggest:
public Collection<String> doctorsByNumPatients() {
    return doctors.values()
            .stream()
            .sorted(Comparator.comparing((Doctor d) -> d.getPatients().size()).reversed())
            .map(d -> String.format("%3d %s", d.getPatients().size(), d.toString()))
            .collect(Collectors.toList());
}

As suggested in the comments I am avoiding the intermediate map, just sorting the doctors by number of patients.
Obviously it can be done the way you tried in the question, and it’s not downright stupid. The part you are missing could go like
    return a.entrySet()
            .stream()
            .flatMap(e -> e.getValue().stream().map((String s) -> String.format("%3d %s", e.getKey(), s)))
            .collect(Collectors.toList());

flatMap() is the operation to use when each element in your stream contains a collection and you want to process each element of the inner collection as an element in the outer stream. In the map() operation in the inner stream we have access to both the inner element, s, and the outer element, e.

