Java 8 Lambda: Comparator

前端 未结 7 1446
鱼传尺愫
鱼传尺愫 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:47

    You should change

     messagesByDeviceType.sort(
         (Message o1, Message o2) -> o1.getTime() - o2.getTime()
     );
    

    to

    messagesByDeviceType.sort(
        Comparator.comparing((Message m) -> m.getTime())
    );
    

    That assumes that the value is Comparable, which provides a natural sort order.

    If you want to add more fields then you can can chain them to the Comparator. e.g. to sort first by time, and then by sender:

    messagesByDeviceType.sort(
        Comparator
            .comparing((Message m) -> m.getTime())
            .thenComparing((m)     -> m.getSender())
    );
    

    To reverse the order of any Comparator, chain the reveresed() method to it, e.g. to sort first by time descending, and then by sender:

    messagesByDeviceType.sort(
        Comparator
            .comparing((Message m) -> m.getTime())
            .reversed()
            .thenComparing((m)     -> m.getSender())
    );
    

    See also https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html

    0 讨论(0)
提交回复
热议问题