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

前端 未结 17 2076
醉酒成梦
醉酒成梦 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:36

    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Comparator;
    
    public class TestClass {
    
        public static void main(String[] args) {
    
            Student s1 = new Student("1","Nikhil");
            Student s2 = new Student("1","*");
            Student s3 = new Student("1",null);
            Student s11 = new Student("2","Nikhil");
            Student s12 = new Student("2","*");
            Student s13 = new Student("2",null);
            List list = new ArrayList();
            list.add(s1);
            list.add(s2);
            list.add(s3);
            list.add(s11);
            list.add(s12);
            list.add(s13);
    
            list.sort(Comparator.comparing(Student::getName,Comparator.nullsLast(Comparator.naturalOrder())));
    
            for (Iterator iterator = list.iterator(); iterator.hasNext();) {
                Student student = (Student) iterator.next();
                System.out.println(student);
            }
    
    
        }
    
    }
    

    output is

    Student [name=*, id=1]
    Student [name=*, id=2]
    Student [name=Nikhil, id=1]
    Student [name=Nikhil, id=2]
    Student [name=null, id=1]
    Student [name=null, id=2]
    

提交回复
热议问题