按属性对自定义对象的

按属性对自定义对象的

本文介绍了按属性对自定义对象的 ArrayList 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了关于使用比较器对 ArrayList 进行排序的文章,但在所有示例中,人们都使用了 compareTo,根据一些研究,它是一种用于字符串的方法.

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.

我想通过自定义对象的一个​​属性对自定义对象的 ArrayList 进行排序:Date 对象(getStartDay()).通常我通过 item1.getStartDate().before(item2.getStartDate()) 来比较它们,所以我想知道我是否可以写类似的东西:

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);
    ...
}

推荐答案

自从 Date 实现了 Comparable,它有一个 compareTo 方法,就像 String 一样.

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

所以您的自定义 Comparator 可能看起来像这样:

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());
    }
}

compare() 方法必须返回一个 int,所以你不能像你计划的那样直接返回一个 boolean.

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());
    }
});


由于 java-8

您现在可以使用 lambda 表达式以更短的形式编写最后一个示例 用于 Comparator:

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

List 有一个 sort(Comparator) 方法,所以你可以进一步缩短它:

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

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

这是一个很常见的习语,以至于有 一种内置方法,用于为具有 Comparable 键的类生成 Comparator:

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.

这篇关于按属性对自定义对象的 ArrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:49