Based on the following answer: https://stackoverflow.com/a/30202075/8760211
How to sort each group by stud_id and then return a List with all Students as result of the g
try sort first and then groupinBy it works well. The below code sorts the Students within the location.
students.stream().sorted().collect(Collectors.groupingBy(Student::getLocation))
The output in this case is
{New York=[1726 John New York, 3442 Mark New York, 5223 Michael New York], Los Angeles=[2234 Andrew Los Angeles], California=[4321 Max California, 7765 Sam California]}
If you would like to have locations also to be sorted, use a code snippet like below
students.stream().sorted().collect(Collectors.groupingBy(Student::getLocation, TreeMap::new, Collectors.toList()))
The output in this case is
{California=[4321 Max California, 7765 Sam California], Los Angeles=[2234 Andrew Los Angeles], New York=[1726 John New York, 3442 Mark New York, 5223 Michael New York]}
Student class implements Comparable and the compareTo method is is based on the id.