Sorting and grouping a list of objects by type and date with variable size data


I am working on a problem. I have to prepare a destination list that is used to show data on UI. Source list is list returned by external webservice.

source list of objects size can be 0 to 16. Another list needs to be formed with max of 8 objects.

object properties are name, type, availableUntilDate and few other.

Ideally new list should have 4 objects of type "NEW" and 4 "non-NEW". Non-New could be used, like-new, mint etc.

If the source list doesn't have at least 4 objects of type "NEW" then non-NEW objects can be taken. Similarly if the source list doesn't have at least 4 non-new, then "new" can be used to fill the destination list.

Each group should be sorted by "NEW" first with latest availableUntilDate.

Can someone give me pointers or algorithm.

Below is ideal result of destination list:

**book_name  type  availableUntilDate** 

Book1      NEW    4/15/2014 6 PM
Book2      NEW    4/15/2014 7 PM
Book3      NEW    4/15/2014 8 PM
Book4      NEW    4/15/2014 9 PM

Book5      OLD    4/15/2014 5 PM
Book6      MINT   4/15/2014 5.30 PM
Book7      OLD    4/15/2014 7 PM
Book8      MINT   4/15/2014 8.30 PM

My idea is to create two temp lists. New list and Non-New List. While looping, each object is added to corresponding list by checking type. If the size of any list is 4, new objects will not be added. After the loop, merge the two lists. I am stuck at how to handle this if the ideal case is not satisfied by source list.

Don't limit the temp lists to four items each. Assuming you have a list with all of the new items and another list with all of the non-new items, the outline of a solution is:

while (!goalReached()) {
    int progress = answer.addFrom(newItems) + answer.addFrom(oldItems);
    if (progress == 0) break;
Collections.sort(answer, myComparator);


  • goalReached needs to return true if the answer has 8 items.

  • addFrom has to remove the best item from the arg and add it to answer, returning 0 if no item is available, 1 otherwise.

  • myComparator has to sort first by type, then by date.