我读过关于使用比较器排序数组列表的内容,但在所有的例子中,人们都使用了compareTo,根据一些研究,它是字符串的一种方法。

我想根据自定义对象的一个属性(Date对象)对其数组列表进行排序 (getStartDay())。通常我通过item1.getStartDate().before(item2.getStartDate())比较它们,所以我想知道我是否可以写一些像这样的东西:

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://www.java67.com/2017/07/how-to-sort-arraylist-of-objects-using.html

其他回答

您可以使用Bean Comparator对自定义类中的任何属性进行排序。

这些代码片段可能很有用。如果你想对一个对象进行排序 在我的例子中,我想按VolumeName排序:

public List<Volume> getSortedVolumes() throws SystemException {
    List<Volume> volumes = VolumeLocalServiceUtil.getAllVolumes();
    Collections.sort(volumes, new Comparator<Volume>() {
        public int compare(Volume o1, Volume o2) {
            Volume p1 = (Volume) o1;
            Volume p2 = (Volume) o2;
            return p1.getVolumeName().compareToIgnoreCase(
                    p2.getVolumeName());
        }
    });
    return volumes;
}

这个作品。我在jsp中使用它。

您的自定义类可以实现“Comparable”接口,这需要CompareTo方法的实现。在CompareTo方法中,您可以定义一个对象小于或大于另一个对象意味着什么。所以在你的例子中,它看起来是这样的:

public class MyCustomClass implements Comparable<MyCustomClass>{

..........

 @Override
public int compareTo(MyCustomClass a) {
    if(this.getStartDate().before(a.getStartDate())){
        return -1;
    }else if(a.getStartDate().before(this.getStartDate())){
        return 1;
    }else {
        return 0;
    }
}

负数表示它小于与之比较的对象。正数表示这比对象的比较大,零表示对象相等。

然后,可以使用collections.sort(myList)对列表进行排序,而不必输入比较器。如果使用TreeSet或TreeMap等已排序的集合数据结构,则此方法还具有自动排序的优点。

如果您想阅读更多关于Comparable接口的信息,可以查看这篇文章(披露:我是作者;)) https://nullbeans.com/the-java-comparable-interface-automatic-sort-of-collections/

你的customComparator类必须实现java.util.Comparator才能被使用。 它还必须覆盖compare() AND equals()

compare()必须回答这个问题:对象1是否小于、等于或大于对象2?

完整文档:http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html

您可以在2016年德国斯图加特的Java论坛上看一看这个演讲。

只有少数幻灯片使用德语,99%的内容是“基于英语”的Java源代码;就像

someCollection.sort(
  OurCustomComparator
    .comparing(Person::getName)
    .thenComparing(Person::getId)
);

其中OurCustomComparator使用默认方法(和其他有趣的想法)。如图所示,导致非常简洁的代码,以选择一些getter方法进行排序;以及超级简单的排序标准链接(或反转)。

如果你对java8感兴趣,你可以在那里找到很多材料来开始学习。