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

前端 未结 10 1393
心在旅途
心在旅途 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条回答
  • 2020-12-29 22:56

    The Java 8 version:

    list.sort(Comparator.comparing(Object::toString));
    

    Or streaming:

    List<Foo> sortedList = unsortedList
        .stream()
        .sorted(Comparator.comparing(Object::toString)))
        .collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-12-29 23:00

    lambdaj allows you to sort, filter and in general manipulate collections without writing loops or obscure inner classes. For example the sorting you were asking can be achieved as it follows:

    sort(foos, on(Foo.class).toString());
    

    If you are interested in it check it out at:

    http://code.google.com/p/lambdaj/

    0 讨论(0)
  • 2020-12-29 23:03

    I would strongly advise you to only use toString for debugging purposes... however... to expand on what Yuval A wrote above...

    public class X
        implements Comparator
    {
        public int compare(final Foo a, final Foo b) 
        {
            return (a.toString().compareTo(b.toString()));
        }
    }
    

    However you really should have Foo implement Comarable or write a proper Compartor that does not make use of toString.

    0 讨论(0)
  • 2020-12-29 23:06

    I would do something very similar to Pierre:

    public class Foo implements Comparable<Foo>
    {
        private String aField;
    
        @Override
        public String toString()
        {
            return aField;
        }
    
        public int compareTo(Foo o)
        {
            return this.toString().compareTo(o.toString());
        }
    }
    

    Then, like Pierre, I would use Collections.sort(list) as Pierre suggests.

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