三生石@ 2010-05-06 21:09 采纳率: 100%
浏览 575
已采纳

按属性对自定义对象排序

I read about sorting ArrayLists using a Comparator but in all of the examples people used compareTo which according to some research is a method for Strings.

I wanted to sort an ArrayList of custom objects by one of their properties: a Date object (getStartDay()). Normally I compare them by item1.getStartDate().before(item2.getStartDate()) so I was wondering whether I could write something like:

public class CustomComparator {
    public boolean compare(Object object1, Object object2) {
        return object1.getStartDate().before(object2.getStartDate());
    }
}

public class RandomName {
    ...
    Collections.sort(Database.arrayList, new CustomComparator);
    ...
}

转载于:https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property

  • 写回答

21条回答 默认 最新

  • csdnceshi62 2010-05-06 21:18
    关注

    Since Date implements Comparable, it has a compareTo method just like String does.

    So your custom Comparator could look like this:

    public class CustomComparator implements Comparator<MyObject> {
        @Override
        public int compare(MyObject o1, MyObject o2) {
            return o1.getStartDate().compareTo(o2.getStartDate());
        }
    }
    

    The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.

    Your sorting code would be just about like you wrote:

    Collections.sort(Database.arrayList, new CustomComparator());
    

    A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:

    Collections.sort(Database.arrayList, new Comparator<MyObject>() {
        @Override
        public int compare(MyObject o1, MyObject o2) {
            return o1.getStartDate().compareTo(o2.getStartDate());
        }
    });
    

    Since java-8

    You can now write the last example in a shorter form by using a lambda expression for the Comparator:

    Collections.sort(Database.arrayList, 
                            (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
    

    And List has a sort(Comparator) method, so you can shorten this even further:

    Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
    

    This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:

    Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));
    

    All of these are equivalent forms.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(20条)

报告相同问题?

悬赏问题

  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。
  • ¥15 stm32的can接口不能收发数据
  • ¥15 目标检测算法移植到arm开发板
  • ¥15 利用JD51设计温度报警系统