groovy - 将 max 与 GPathResults 列表一起使用

标签 groovy xml-parsing

我有一个 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/

相关文章:

java - 使用java中的Document删除xml中的节点

ios - 如何解析响应标记内包含 XML 文档的 SOAP 响应

Groovy:for..in 比 .each 快得多吗?

json - 连接 JSONArray 会向 groovy 中的字符串添加双引号

java - 在 Java 中加载相互依赖的 groovy 类

ruby - 使用 REXML Document 和 Ruby 获取元素的 InnerXML

javascript - 执行某些操作后检查 Javascript 变量的内容

java - Web 元素 Groovy isSelected() 和 selected 得到错误的结果

groovy - 为什么 DataFlow 变量只能分配一次

swift - 从 RSS 或网页解析 XML