我有一个 GPathResults 列表,其中都有一个属性“seq” 例如:
GPathResult gath;
Integer int = gath.seq.toInteger()
现在我想选择具有最大“seq”的 GPathResult?
如果我有 10 个 GPathResult,其中有 10 个“seq”值,我需要获取具有最大“seq”值的 GPathResult
除了将每个 GPathResult 与下一个 GPathResult 进行比较之外,是否有任何更 Groovier 的方法可以做到这一点?
最佳答案
您可以使用max
method that takes a Closure
def gpathWithMaxSeq = listOfGpaths.max { it.seq.toInteger() }
来自文档:
If the closure has two parameters it is used like a traditional Comparator. [...] Otherwise, the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) which is then used for further comparison.
如果某些 GPathResults 可能没有 seq
那么您可能需要更多类似这样的内容(未经测试)
def gpathWithMaxSeq = listOfGpaths.max {
it.seq ? it.seq.toInteger() : Integer.MIN_VALUE
}
(MIN_VALUE
使没有 seq
的项目比有 seq
的项目小)。
关于groovy - 将 max 与 GPathResults 列表一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20097579/