Using Comparable for multiple dynamic fields of VO in java

后端 未结 7 1884
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 11:36

I have a class

public class StudentVO {
   int age;
   String name;  
}

I used the same class in two different areas. At one place i need t

7条回答
  •  悲哀的现实
    2020-11-28 12:03

    Anton's approach is quite good. I use this one:

    1- For sorting only by age:

    Collections.sort( studentList, Comparator.comparingInt( student -> student.getAge() ) );
    

    2- For name:

    Collections.sort( studentList, Comparator.comparing( student -> student.getName() ) ); 
    

    3- Combination:

    Collections.sort( studentList, Comparator.comparing( student -> student.getName() ).thenComparingInt( student -> student.getAge() ) ); 
    

提交回复
热议问题