Home » Java » java – Sort a list of abstract objects based on their child's field-Exceptionshub

java – Sort a list of abstract objects based on their child's field-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

My abstract object :

public abstract class ContentEntry {
    private double score;
}

ContentEntry has four children, two of them (Movie and Song) having the field long date;

I have a List<ContentEntry> that I was previously sorting by score with :

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

I would now like to sort by date but I don’t see how using Comparator. Thx!

How to&Answers:

Obviously, you first have to define how instances of classes without the date field are compared, and how they compare to objects that have a data field.

Once this is done you can define a class

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

Note that it may be better to introduce a function getSortKey() that returns the key that is used for sorting. That function could be overridden by classes like Movie and Song. The could return something that includes the date.