tylerBrignone
tylerBrignone

Reputation: 45

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?

Upvotes: 0

Views: 85

Answers (2)

Luke
Luke

Reputation: 490

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> {

    @Override
    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.

Upvotes: 1

D.B.
D.B.

Reputation: 4713

As some comments have already pointed out you could use a Comparator. Another option is to implement the Comparable interface. Here's some good info regarding the difference

Upvotes: 1

Related Questions