Finding a value of a list - groovy

I have two lists
def flagList = SystemFlag.list()
this contains the domain objects of one table
I have another list which I create using a query. One of the parameter in the object of this list is contained in the flagList. How can I find if an id of FlagList is present in the second list?
I can do it in plain java but I need to use Groovy for this.

If I understood you correctly you have this situation:
def listeOne = [1,2,3,4,5]
def listTwo = [2,5,1]
You want to see if '2' of 'listTwo' is in 'listOne'.
Find a specific value:
def found = 2 in listTwo //returns a boolean of the interger 2 is in listTwo
Search for common value of both lists:
def intersectionsList = listOne.intersect(listTwo) //gives you a list of value that are in BORTH list
You can also iterate like this:
listTwo.each { value ->
if(value in listOne) println value //or do something lese
}
Alternatively:
listTwo.each { value ->
listOne.find {value}?.toString() //you can perform an action on the object found in listOne. using '?.' will make sure no nullpointer will be thrown if there is no result.
}

I found it using
def it = itemtofindsomehow
list.findIndexof { iterator ->
iterator.domain.id == it.id
}

Related

Groovy remove null elements from a map

I am getting a map in my method from another server and I have some null values, I wanted to remove those ones, because I am struggling with those values in the following process:
My map looks something like:
I had done the next code, but without satisfactory results:
map.values().removeAll(Collections.singleton(null))
Any ideas?
Thanks
Edit
The Groovy way, is to filter the entries you want:
def map = [a:42, b:null]
def cleanMap = map.findAll{ it.value!=null }
println cleanMap
// => [a:42]
Previous answer:
Seems to work with Jdk8/Groovy 2.5, but not for OP
To remove all elements with a value with null, remove on the map directly:
def map = [a:42, b:null]
map.removeAll{ it.value == null }
println map
// => [a:42]

Checking a value across multiple arrays

I have a context property named 'flights'. I want to check if there is no value for this property, then go to the 'Iteration' test step, else set the first value of the property as a test case property.
Now what I want to do is perform a compare using this test case property value with a couple of arrays. Below is the scenario;
Check if value is in the villas array, if so +1 to VillasCount, else check in hotels array, if in there then +1 to beachCount else +1 to noCount.
Code is below:
// define properties required for the script to run.
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def dataFolder = groovyUtils.projectPath
//Define an empty array list to load data from datasheet
def dataTable_properties = [];
int villasCount = context.getProperty("villasCount")
def lines = new File(dataFolder + "/Test.csv").readLines()
def villas = []
lines.eachWithIndex { line, index ->
if (index) {
def data = line.split(',')*.trim()
if (data[0]) villas << data[0]
}
}
log.info "Villas : ${villas}"
context.setProperty("villasCount", villasCount)
Maybe something like:
for(f in flights){
if(villas.contains(f)){
villasCount = villasCount + 1
}
}
Not 100% sure what you needed to compare, but you could easily expand this to check whatever you wanted.
If this is way off please provide more information on what you were trying to compare.

Retrieve value in map by key in Groovy

def text= '''<Rollback> <Kits>
<Kit ServerName='ust1twastool01a'>
<Backup>2016-10-18_20_34-46-_server-21.000.409_client-21.000.407.zip</Backup>
<Backup>2016-10-18_21_57-33-_server-21.000.409_client-21.000.407.zip</Backup>
<Backup>2016-10-19_02_40-03-_server-21.000.413_client-21.000.407.zip</Backup>
<Backup>2016-10-19_13_58-36-_server-21.000.413_client-21.000.407.zip</Backup>
<Backup>2016-10-20_03_14-34-_server-21.000.413_client-21.000.407.zip</Backup>
</Kit>
<Kit ServerName='another_server'>
<Backup>123123.zip</Backup>
<Backup>321321.zip</Backup>
</Kit>
</Kits></Rollback>'''
def xml = new XmlSlurper().parseText(text)
def map = [:]
i = 0
xml.Kits.Kit.each{node->
def list = []
node.Backup.each{kit->
list.add(kit)
}
map.put(node.#ServerName, list)
}
print map // print map with all keys and values
// Somehow, it's not working ...
print map['ust1twastool01a']
def map2 = ['1':["abc","123"], '2':["bcd", "456"]]
print map2['1']
​
I have been annoyed by the above code for almost the day. I don't understand why I can't get value by map['ust1twastool01a'].
I attached a screenshot from a console, it shows that map is not empty but just can't get its value by key. map2 is just control group as it has the similar structure to map string as key and list as value
Use as below:
map.put(node.#ServerName.text(), list)
On a side note, I believe you can simplify the code to just:
def xml = new XmlSlurper().parseText(text)
def map = xml.Kits.Kit.collectEntries { node ->
[ node.#ServerName.text(), node.Backup.collect() ]
}

Find a value in a collection and assign top an variable using groovy

Hello Groovy Experts,
I am using the below command to get all the ODI Dataservers.
def PSchema=DServer.getPhysicalSchemas();
When I print the PSchema variable I getting the following values.
[oracle.odi.domain.topology.OdiPhysicalSchema ABC.X1, oracle.odi.domain.topology.OdiPhysicalSchema ABC.X2]
What I am trying to achieve here I will be passing X1 or X2 during runtime...
And then I want to validate this value with the PSchema result and the print the following value:
oracle.odi.domain.topology.OdiPhysicalSchema ABC.X2
I tried using the following options:
def PSchema44 = PSchema11.findIndexValues { it =~ /(X1)/ }
def pl=PSchema11.collect{if(it.contains ('X1)){return it}}
I tried for loop to check whether values are getting printed properly ..result is fine:
for (item in PSchema11 )
{
println item
}
Assuming 'X1' and 'X2' are the names for the physical schemas, you should be able to do something like this:
def phys = "X1"
def pSchemas = dServer.getPhysicalSchemas()
def schema = pSchemas.find{it.schemaName == phys}
also I guess you are new to Groovy, I suggest you read up on syntax and naming conventions. For example, variable names should always start with a lower case letter

Is there a functional programming way to retrieve the first element of a collection?

The list can be empty. I would like to do :
def value = "";
def list = getList()
if (!list.isEmpty()){
value = list.first().foo
}
for instance I have found this way :
assert ( [].find()?.foo?:"empty" ) == "empty"
assert ([[foo:"notEmpty1"], [foo:"notEmpty2"]].find()?.foo?:"empty") == "notEmpty1"
Is there a better way ?
Thanks! :)
EDIT:
I got great answer by using [0]
assert ( [][0]?.foo?:"empty" ) == "empty"
assert ([[foo:"notEmpty1"], [foo:"notEmpty2"]][0]?.foo?:"empty") == "notEmpty1"
If it is a List just try
if (!list?.isEmpty()){
list.get(0);
}
If the list element cannot be null you don't need the ?
If it is a Collection there are several forms to retrieve it. Take a look at this post
Java: Get first item from a collection
I got an answer from tweeter. The statements :
def value = "";
def list = getList()
if (!list.isEmpty()){
value = list.first().foo
}
Can be write :
def value = list[0]?.foo?:""
find may be use if the list can contain null values

Resources