so, there is a class called City which has two fields (Name and Population) and the usual getters and setters. now my question is why can i sort cities by name just fine like this
public class Main{
public static void main(String[] args) {
List<City> list = List.of(new City("Tokyo", 7), new City("Mexico City", 1),
new City("São Paulo", 3), new City("Lagos", 5),
new City("Istanbul", 4), new City("Sydney", 6),
new City("McMurdo", 2));
List<String> listOfNames = list.stream().sorted((City o1, City o2) -> o1.getName().compareTo(o2.getName())).map(City -> City.getName()).collect(Collectors.toList());
listOfNames.forEach(Element -> System.out.println(Element));
}
}
but I can only sort by population like this(in descending order)
List<String> listOfNames = list.stream().sorted((City o1, City o2) -> o2.getPopulation() - o1.getPopulation()).map(City -> City.getName()).collect(Collectors.toList());
Why is this approach wrong
List<String> listOfNames = list.stream().sorted((City o1, City o2) -> Comparator.comparingInt(o1.getPopulation(), o2.getPopulation())).map(City -> City.getName()).collect(Collectors.toList());
why can't I use compare/compareTo like i did when sorting be name(String)
PS
I did not implement comparable or have a Comparator in my code