Java 8 Lambda: Comparator

前端 未结 7 1463
鱼传尺愫
鱼传尺愫 2021-02-01 12:53

I want to sort a list with Lambda:

List messagesByDeviceType = new ArrayList();      
messagesByDeviceType.sort((Message o1, Messag         


        
7条回答
  •  太阳男子
    2021-02-01 13:39

    Lambda

    The lambda can be seen as the shorthand of somewhat cumbersome anonymous class:

    Java8 version:

    Collections.sort(list, (o1, o2) -> o1.getTime() - o2.getTime());
    

    Pre-Java8 version:

        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Message o1, Message o2) {
                return o1.getTime() - o2.getTime();
            }
        }); 
    

    So, every time you are confused how to write a right lambda, you may try to write a pre-lambda version, and see how it is wrong.

    Application

    In your specific problem, you can see the compare returns int, where your getTime returns long, which is the source of error.

    You may use either method as other answer method, like:

    Long.compare(o1.getTime(),o2.getTime())
    

    Notice

    • You should avoid using - in Comparator, which may causes overflow, in some cases, and crash your program.

提交回复
热议问题