Search code examples
arraysgroovymaxmin

How to get min and max value from a group array in Groovy


I'm fairly new to Groovy and I don't know where to begin with this problem. I have a xml file that contains multiple entries with rid, id and a date. I've managed to get the elements into an array and I would like to extract rid, min date and max date grouped by each rid. If there is only one entry in the group, min and max date would be the same.

Data:
1,1234,2022010101;
2,1235,2022020202;
2,1236,2022030303;

Preferred output:
1,2022010101,2022010101;
2,2022020202,2022030303;

Solution

  • Try something like this:

    def dataLines = [
        [1,1234,2022010101],
        [2,1235,2022020202],
        [2,1236,2022030303]
    ]
    
    def output = dataLines.groupBy { it[0] }.collect { rid, lines ->
        def sorted = lines.sort{ it[2] }
        [ rid , sorted[0][2], sorted[-1][2] ]
    }
    
    output.each { println it }