How does Java 8 Stream: sort by an attribute under a sub-object in an object?

I have an object List, such as List < Main >, a property in Main is a Sub object, and an attribute id in Sub.
I want to sort by Main.Sub.id. What should I do?

list < Main > .stream (). Sorted (Comparator.comparing (Main::getSub)) cannot be sorted by id.

Mar.02,2021

list.stream (). Sorted ((Sub1, Sub2)-> Sub1.getId (). CompareTo (Sub2.getId (). Collect (Collectors.toList ());


are you sure that answer is valid?

Menu