Collections sort не сортирует по имени

По возрасту работает запросто

Human first = new Human("aaa", 11);
Human sec = new Human("bbb", 1111);
Human th = new Human("ccc", 19);

List<Human> humans = new ArrayList<>();
humans.add(first);
humans.add(sec);
humans.add(th);


// Сортировка по возрасту
Collections.sort(humans, new Comparator<Human>() {
    @Override
    public int compare(Human o1, Human o2) {
        return o1.age - o2.age;
        //  return o1.name.compareTo(o1.name);
    }
});
System.out.println("Сортировка по возрасту");
for (Human human : humans) {
    System.out.println(human.getName() + " " + human.getAge());
}

// Сортировка по имени
Collections.sort(humans, new Comparator<Human>() {
    @Override
    public int compare(Human o1, Human o2) {
        //   return o1.age - o2.age;
        return o1.name.compareTo(o1.name);
    }
});
System.out.println("Сортировка по имени");
for (Human human : humans) {
    System.out.println(human.getName() + " " + human.getAge());
}
    

Результат

Сортировка по возрасту
aaa 11
ccc 19
bbb 1111

Сортировка по имени
aaa 11
ccc 19
bbb 1111

Ответы (1 шт):

Автор решения: Nowhere Man

Проще использовать компаратор по заданному свойству Comparator.comparing(Function<? super T,? extends U> keyExtractor), для чего достаточно передать ссылку на метод-геттер для нужного свойства/поля:

Collections.sort(humans, Comparator.comparing(Human::getName));
→ Ссылка