根据抽象对象的子字段对抽象对象的列表进行排序



我的抽象对象:

public abstract class ContentEntry {
private double score;
}

ContentEntry有四个子项,其中两个子项(MovieSong(具有字段long date;

我有一个List<ContentEntry>,我以前用score进行排序:

.flatMap(entries -> Flux.fromIterable(entries)
.sort(Comparator.comparing(ContentEntry::getScore))
.collectList()
)

我现在想按date排序,但我不知道如何使用Comparator。Thx!

显然,您首先必须定义如何比较没有date字段的类的实例,以及如何将它们与具有data字段的对象进行比较。

完成后,您可以定义一个类

class MyComparator implements Comparator<ContentEntry> {
public int compare(ContentEntry e1, ContentEntry e2) {
long date1 = -1; // Date of first entry, -1 indicates "no date"
long date2 = -1; // Date of first entry, -1 indicates "no date"
if ( e1 instanceof Movie ) date1 = ((Movie)e1).date;
else if ( e1 instanceof Song ) date1 = ((Song)e1).date;
if ( e2 instanceof Movie ) date2 = ((Movie)e2).date;
else if ( e2 instanceof Song ) date2 = ((Song)e2).date;
// Now compare based on date1, date2, and potentially other things
...
}
}

请注意,最好引入一个函数getSortKey(),该函数返回用于排序的密钥。该函数可以被MovieSong等类覆盖。可以返回包含日期的内容。

最新更新