How to simplify a null-safe compareTo() implementation?

前端 未结 17 2089
醉酒成梦
醉酒成梦 2020-11-28 18:03

I\'m implementing compareTo() method for a simple class such as this (to be able to use Collections.sort() and other goodies offered by the Java pl

17条回答
  •  死守一世寂寞
    2020-11-28 18:40

    we can use java 8 to do a null-friendly comparasion between object. supposed i hava a Boy class with 2 fields: String name and Integer age and i want to first compare names and then ages if both are equal.

    static void test2() {
        List list = new ArrayList<>();
        list.add(new Boy("Peter", null));
        list.add(new Boy("Tom", 24));
        list.add(new Boy("Peter", 20));
        list.add(new Boy("Peter", 23));
        list.add(new Boy("Peter", 18));
        list.add(new Boy(null, 19));
        list.add(new Boy(null, 12));
        list.add(new Boy(null, 24));
        list.add(new Boy("Peter", null));
        list.add(new Boy(null, 21));
        list.add(new Boy("John", 30));
    
        List list2 = list.stream()
                .sorted(comparing(Boy::getName, 
                            nullsLast(naturalOrder()))
                       .thenComparing(Boy::getAge, 
                            nullsLast(naturalOrder())))
                .collect(toList());
        list2.stream().forEach(System.out::println);
    
    }
    
    private static class Boy {
        private String name;
        private Integer age;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public Boy(String name, Integer age) {
            this.name = name;
            this.age = age;
        }
    
        public String toString() {
            return "name: " + name + " age: " + age;
        }
    }
    

    and the result:

        name: John age: 30
        name: Peter age: 18
        name: Peter age: 20
        name: Peter age: 23
        name: Peter age: null
        name: Peter age: null
        name: Tom age: 24
        name: null age: 12
        name: null age: 19
        name: null age: 21
        name: null age: 24
    

提交回复
热议问题