How to sort the name along with age in java

后端 未结 8 1200
失恋的感觉
失恋的感觉 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-18 00:08

    This is simple one liner comparison using ternary operator for sorting the objects. No need to write so many if/else block.

    Collections.sort(persons, new Comparator() {
    
        @Override
        public int compare(Person t1, Person t2) {
    
            return t1.getFname().equals(t2.getFname()) ? t1.getAge()-t2.getAge() : t1.getFname().compareTo(t2.getFname());
    
        }
    });
    

提交回复
热议问题