How to sort the name along with age in java

后端 未结 8 1194
失恋的感觉
失恋的感觉 2021-01-17 23:34

I am new to Java 8. I just want to sort by the name. But the condition is: if there are duplicate names then it should be sorted according to age.

For example my inp

8条回答
  •  萌比男神i
    2021-01-18 00:21

    You are on the right path, but your compare method is incomplete.

    Since compare is called to decide which item in each pair is to go before the other, it must include all comparison logic, not only the tie-breaking one. Your code sorts on the age alone, ignoring the name completely.

    The logic should go like this:

    • Compare names using t.getFname().compareTo(t1.getFname())
    • If names are not the same, return the result of comparison
    • Otherwise, return the result of comparing ages.

    Proper way of comparing integers is with the static Integer.compare method, i.e. Integer.compare(t.getAge(), t1.getAge()).

提交回复
热议问题