tylerBrignone tylerBrignone - 8 months ago 31
Java Question

Sorting object list by 2 different sub-objects in java

I have a DTO class I need to sort, it looks like this:

public class MessagesWithComments {
private Message parentMessage;
private List<Message> childMessages;

My Message class:

public class Message {
private String message;
private Date createdDate;

My service then returns a list of MessagesWithComments.

public List<MessagesWithComments> getParentsWithComments(....) {....}

I need these to be ordered so that the most recent message date of each MessageWithComments comes first, the tricky part is the date can be inside the parentMessage or inside the list of childMessages. So for example:

MessageWithComments 1

parentMessage date = '2016-10-13 10:40pm'
no child messages

MessageWithComments 2

parentMessage date = '2016-10-10 10:40pm'
childMessage date = '2016-10-11 12:31pm'
childMessage date = '2016-10-14 11:21pm'

MessageWithComments 3

parentMessage date = '2016-10-11 10:40am'
childMessage date = '2016-10-12 12:31pm'
childMessage date = '2016-10-13 10:28pm'

So in this example I would have my list of MessagesWithComments return in the order:

2(most recent date of '2016-10-14 11:21pm'),
1(most recent date of '2016-10-13 10:40pm'),
3(most recent date of 2016-10-13 10:28pm')

Is there a standard way of doing this sort of thing or should I add another variable to my MessageWithComments class called 'mostRecentMessageDate' and then sort the list that way?


I suggest using a custom Comparator.

You can implement your Comparator by defining how to compare two MessagesWithComments objects, and then use the Java Collections class to sort.

class MessagesWithCommentsComparator implements Comparator<MessagesWithComments> {

    public int compare(MessagesWithComments o1, MessagesWithComments o2) {
        // parse the MessagesWithComments objects to determine order

Then you can use the Collections class:

Collections.sort(messagesWithCommentsList, new MessagesWithCommentsComparator());

By defining how to compare two MessagesWithComments objects in the MessagesWithCommentsComparator, the Collections class then knows how to sort by using the compare() method that you've overridden.