Using Comparable for multiple dynamic fields of VO in java

后端 未结 7 1853
伪装坚强ぢ
伪装坚强ぢ 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:09

    There is new approach for this in java-8 see Comparator#comparing and Comparator#thenComparing. All you need is to provide a lamda expression/method reference either to Stream#sorted() or List#sort() method.

    For example sorting by one field:

    List students = Arrays.asList(
            new StudentVO(20,"Bob"),
            new StudentVO(19, "Jane")
    );
    // sort by age
    students.stream()
            .sorted(Comparator.comparing(StudentVO::getAge))
            .forEach(System.out::println);
    // [StudentVO{age=19, name='Jane'},StudentVO{age=20, name='Bob'}]
    // sort by name
    students.stream()
            .sorted(Comparator.comparing(StudentVO::getName))
            .forEach(System.out::println);
    // [StudentVO{age=20, name='Bob'}, StudentVO{age=19, name='Jane'}]
    

    Sorting by a few fields:

    List students = Arrays.asList(
            new StudentVO(20,"Bob"),
            new StudentVO(19, "Jane"),
            new StudentVO(21,"Bob")
    );
    // by age and then by name
    students.stream()
            .sorted(Comparator
                    .comparing(StudentVO::getAge)
                    .thenComparing(StudentVO::getName)
            ).forEach(System.out::println);
    // [StudentVO{age=19, name='Jane'}, StudentVO{age=20, name='Bob'}, StudentVO{age=21, name='Bob'}]
    // by name an then by age
    students.stream()
            .sorted(Comparator
                    .comparing(StudentVO::getName)
                    .thenComparing(StudentVO::getAge)
            ).forEach(System.out::println);
    // [StudentVO{age=20, name='Bob'}, StudentVO{age=21, name='Bob'}, StudentVO{age=19, name='Jane'}]
    

提交回复
热议问题