How to sort the name along with age in java

后端 未结 8 1117
失恋的感觉
失恋的感觉 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条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-17 23:55

    Currently you are a) only comparing by one attribute and b) not really making use of Java 8's new features.

    With Java 8 you can use method references and chained comparators, like this:

    Collections.sort(persons, Comparator.comparing(Person::getFname)
        .thenComparingInt(Person::getAge));
    

    This will compare two Person instances first by their fname and - if that is equal - by their age (with a slight optimization to thenComparingInt to avoid boxing).

提交回复
热议问题