Groovy - 如何退出每个循环? [英] Groovy - how to exit each loop?

查看:1072
本文介绍了Groovy - 如何退出每个循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Grails / Groovy的新手,正在尝试在xml文件中查找节点;我已经想出了如何遍历所有这些,但是我想在找到目标节点时退出循环。我读过,而不是使用每个,使用查找,但我看到的查找示例是条件。现在我所拥有的逻辑会在不退出的情况下迭代整个文件。代码如下:

  records.children()。each {domain  - > 
printlndomain_name:+ domain。@ domain_name $ b $ if if(domain。@ domain_name == targetDomain){

printlntarget domain matched:+ domain。@ domain_name

domain.children()。each {misc_field - >

printlnfield_name:+ misc_field。@ field_name
printlnfield_type:+ misc_field。@ field_type
printlnfield_value:+ misc_field

}



}
}


解决方案

你无法做到优雅。你可能会看到有人提出抛出异常,但这只是纯丑陋



以下是一些邮件列表讨论关于使用每个 code>,还有一些人认为对于是首选,因为每个无法从中断迭代。



最好的办法是换成循环并迭代:

  for(def domain:records.children()){//这可能需要根据类型进行一些调整
// do stuff
if(condition){
break;


$ / code $ / pre

或者像你说的那样,也许使用< a href =http://groovy.codehaus.org/Quick+Start#QuickStart-find =nofollow noreferrer> find 或 findAll 找到您要查找的元素(下面的代码被解释,我没有时间去测试它):

  def result = records.children()。find {domain  - > domain。@ domain_name == targetDomain} 
result.children()。each {
// print stuff
}

相关SO问题:


I'm new to Grails/Groovy and am trying to find a node in a an xml file; I've figured out how to iterate over all of them, but I want to exit the loop when the target node is found. I've read that instead of using "each", use "find", but the find examples I've seen are conditions. Right now the logic I have is going to iterate through the whole file without exiting. The code is below:

  records.children().each {domain ->
   println "domain_name: " + domain.@domain_name
   if (domain.@domain_name == targetDomain) {

    println "target domain matched: " + domain.@domain_name

    domain.children().each {misc_field ->

     println "field_name: " + misc_field.@field_name
     println "field_type: " + misc_field.@field_type
     println "field_value: " + misc_field

    }



   }
  }

解决方案

You cannot do it elegantly. You might see some people suggest throwing an Exception, but that's just plain ugly.

Here's some mailing list discussion on using each vs. for, and a couple people say that for is preferred because of each's inability to break from the iteration.

Your best bet is probably to change over to a for loop and iterate:

for(def domain : records.children()) { // this may need some tweaking depending on types
    // do stuff
    if(condition) {
        break;
    }
}

Either that, or like you said, maybe use find or findAll to find the element you're looking for (the following code is paraphrased, I don't have time yet to test it out):

def result = records.children().find { domain -> domain.@domain_name == targetDomain }
result.children().each {
    // print stuff
}

Related SO questions:

这篇关于Groovy - 如何退出每个循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆