Sorting an ArrayList of objects using a custom sorting order

后端 未结 11 1495
说谎
说谎 2020-11-22 00:14

I am looking to implement a sort feature for my address book application.

I want to sort an ArrayList contactArray. Contact

11条回答
  •  北海茫月
    2020-11-22 00:44

    Ok, I know this was answered a long time ago... but, here's some new info:

    Say the Contact class in question already has a defined natural ordering via implementing Comparable, but you want to override that ordering, say by name. Here's the modern way to do it:

    List contacts = ...;
    
    contacts.sort(Comparator.comparing(Contact::getName).reversed().thenComparing(Comparator.naturalOrder());
    

    This way it will sort by name first (in reverse order), and then for name collisions it will fall back to the 'natural' ordering implemented by the Contact class itself.

提交回复
热议问题