Sort and group the list of objects by type and date with resizing data

I am working on a problem. I need to prepare a mailing list that is used to display data in the user interface. A source list is a list returned by an external web service.

The initial list of objects can be from 0 to 16. Another list must be formed with a maximum of 8 objects.

Object properties are name, type, availabilityUntilDate and a few others.

Ideally, a new list should have 4 "NEW" and 4 "non-NEW" objects. Non-New can be used, such as new, mint, etc.

If the original list does not contain at least 4 objects of type "NEW", then non-NEW objects can be made. Likewise, if the source list does not contain at least 4 not new ones, then you can use "new" to fill the destination list.

Each group must be sorted with "NEW" first with the last available UntilDate.

Can someone give me pointers or an algorithm.

Below is the ideal mailing list result:

**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 temporary lists. New list and new list. During cyclization, each object is added to the corresponding list, checking the type. If the size of any list is 4, no new objects will be added. After the loop, combine the two lists. I am stuck on how to handle this if the ideal case is not satisfied with the source list.


source to share

2 answers

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

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



  • goalReached

    should return true if the response contains 8 elements.

  • addFrom

    should remove the best element from arg and add it in answer

    , returning 0 if the element is not available, 1 otherwise.

  • myComparator

    must sort first by type, then by date.



The solution is to use comparators:
    //whatever you want to do with them


This will give you a stream of books



All Articles