Search code examples
grailsfindby

Find latest entries in a list based on a field


I'm not even sure how to search if this is an existing questions. Let me just give an example:

Call Instance   Date Created           Resource    Resource Status
------------------------------------------------------------------
6557            2013-07-12 11:34:19    cwood       Accepted
6556            2013-07-12 11:34:18    cwood       Accepted
                2013-07-12 11:29:25    cwood       Ready
6555            2013-07-12 09:24:41    cwood       Accepted

How do I get the top two Accepted entries off the top without getting the last Accepted entry (as it came before a Ready entry)?

All the fields except for Date Created are user-defined classes (Call, User [no, not Resource], and ResourceStatus).

Please let me know if further code would be useful.


Solution

  • You can use takeWhile():

    ​assert [1,2] == [1,2,3,4,5].takeWhile { it < 3 }​
    

    EDIT(Audacity of @dmahapatro to edit answer)
    Small test case for available statuses other than Accepted and Ready:

    def list = ['A', 'A', 'B', 'A', 'R', 'A']
    assert list.takeWhile{ it == 'A'} == ['A', 'A']
    assert list.takeWhile{ it != 'R'} == ['A', 'A', 'B', 'A']