Alphabetically Sort a Java Collection based upon the 'toString' value of its member items

前端 未结 10 1450
心在旅途
心在旅途 2020-12-29 22:10

Assume I have a user defined Java class called Foo such as:

public class Foo 
{

    private String aField;

    @Override
    public String toString()
    {         


        
10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 22:50

    google-collections makes this really easy with Ordering:

    Collections.sort(list, Ordering.usingToString());
    

    Is bringing in a whole 3rd-party library just to use something you could write trivially using a Comparator (as others have provided) worthwhile? No, but google-collections is so cool you'll want to have it anyway for a bunch of other reasons.

    On the sorting front, you can also easily do things like reversing:

    Ordering.usingToString().reverse();
    

    or break ties:

    Ordering.usingToString().compound(someOtherComparator);
    

    or deal with nulls:

    Ordering.usingToString().nullsFirst();
    

    etc., but there's a bunch more stuff in there (not just sorting-related, of course) that leads to really expressive code. Check it out!

提交回复
热议问题