0

I'm very new to groovy so please excuse if its a silly question.

I'm parsing a XML file and fetching the fruit names to a list. My incomplete code snippet below.

....
....
def xmlOutput = proc.in.text
def lists = new XmlSlurper().parseText(xmlOutput)
def listOffruits = lists.fruits.entry.name

//Below is the fuit list for which I want to skip the loop
def myList = ["orange", "apple", "banana", "grapes"]

listOffruits.each(){
  def fruitName = it.text()
    //Not sure how on the logic
println "- found Fruit Name not on the list'${fruitName }'"
}

I want to check/compare if the fruit name is present in the list - "myList" , if present skip the loop or move on to next iterator ,if not continue with the loop.

I'm not sure how exactly to achieve it. Any suggestions pls. Thanks.

voltas
  • 553
  • 7
  • 24
  • 1
    Possible duplicate of http://stackoverflow.com/questions/3049790/break-from-groovy-each-closure – Nitesh Goyal Mar 01 '17 at 10:24
  • @Nitesh , Thanks, but i want to compare/check every value of list - listOffruits to the values in the another list - myList . – voltas Mar 01 '17 at 10:36

2 Answers2

2

You can use findAll to just keep the fruit not in the list...

def unfoundFruits = listOffruits.findAll { f -> !myList.contains(f) }
unfoundFruits.each { f ->
    println "- found Fruit Name not on the list '${f}'"
}
tim_yates
  • 167,322
  • 27
  • 342
  • 338
1

You can use Collection#minus, for example:

def listOffruits = ["pineapple", "apple", "strawberry", "grapes"]
def myList = ["orange", "apple", "banana", "grapes"]
println "Fruits not on the list: ${listOffruits.minus myList}"
m0skit0
  • 25,268
  • 11
  • 79
  • 127