creating a list of object in groovy - groovy

Given the fallowing lists, I need to create a list mapping the items of the list:
def list1=[math,science]
def list2=[90,80]
create listofObj=[{label:"activity score",value:90},{label:"math",value=80}]
I've tried listofObj=[[tablelabels,tablevalues].transpose().collectEntries{[it[0],it[1]]}]
but it's producing a simple mapping.

Your solution is quite close. But the transpose only gives you the
tuples for label/value. If you need a fresh map with the keys, you have
to create it. E.g.
def labels=["math","science"]
def values=[90,80]
println([labels,values].transpose().collect{ label, value -> [label: label, value: value] })
// → [[label:math, value:90], [label:science, value:80]]

Related

How to make Eclipse/PyDev know a variable is being linked to a list?

I've got an object class that is provided a dictionary at __init__(), which in turns contains nested dictionaries. What I want to do is create a shortcut to (in this case) a list that is buried several layers into the dict.
Obviously this will work:
class Example(object):
def __init__(self, foo: dict):
self.shortcut = foo['a']['b']['c']
The problem is that I would like to do this in such a way that Eclipse/PyDev knows that foo['a']['b']['c'] a list (and therefore so is self.shortcut), similar to the way that adding :dict tells PyDev that foo is a dictionary.
The closest I've come to a solution is:
self.shortcut = list( foo['a']['b']['c'] )
But that makes a copy, and I want to preserve the link to foo. I could turn around and do the assignment in reverse, by following it up with
foo['a']['b']['c'] = self.shortcut
But that... that just offends my programming sensibilities.

Get the values of maps in arrayList

I have an arrayList of maps that i generate in my controller and pass to GSP page!
i would like to get the values of the maps as a list to present in g:select in gsp!
as in each element (Map) in the arrayList! The select option value should be the map value and the map key as an optionKey
as i want to use this key in a script when the user choose an option!
sorry am a bit confused if the question is not quite clear!
ArrayList[Map1,Map2,Map3]
Map1[1,value1]
Map2[2,value2]
Map3[3,value3]
// the values are strings to show in select
//the respective key of the option value the user has chosen i want it as option key so i can pass it to script
If I understood correctly you have a list (ArrayList) of Maps and you want to represent each map as a select, right?
Your arraylist of maps could be something like this:
def words_en = ['One':'Apple', 'Two':'Pear', 'Three': 'Strawberry']
def words_it = ['One':'Mela', 'Two':'Pera', 'Three': 'Fragola']
def words_de = ['One':'Apfel', 'Two':'Birne', 'Three': 'Erdbeere']
def myList = [words_en, words_it, words_de]
you can generate the select elements as follows:
<g:each var="myMap" in="${myList}" status="i">
<g:select id="select_${i}" name="select_${i}" optionKey="key" from="${myMap}" optionValue="value" ></g:select> <br/>
</g:each>
EDIT:
With the edited version of your question I understood that you have several maps each containing only one key-value pair. Given that your keys are unique, the best approach is to merge all your maps into one and simply use that to populate the select:
def words_1 = ['One':'Apple']
def words_2 = ['Two':'Pera']
def words_3 = ['Three': 'Erdbeere']
def myList = [words_1, words_2, words_3]
def myMap = [:]
myList1.each{map->
myMap.putAll(map)
}
and in the view:
<g:select id="mySelect" name="mySelect" optionKey="key" from="${myMap}" optionValue="value" ></g:select>

Access element of list by variable name

How can I access a list element using the name of the list?
I would like to allow a user to edit the code in determine a single variable to be inputted into a function. For example:
blah = [1,2]
blah2 = 5
toBeChanged = "blah2"
def foo():
print(blah)
def changeVariable():
globals()[toBeChanged] += 1
for time in range(5):
changeVariable()
simulate
This works for blah2 since it is a simple variable, however it will not work for blah[0] since it is part of a list. I've also tried placing my variables into a dictionary as other answers have suggested, but I still am unable to change list elements through a simple string.
Is there a way to do this that I am missing? Thanks!
Rather than using globals() and altering directly it would be much, much better to use a dictionary to store the variables you want the user to alter, and then manipulate that:
my_variables = {
'blah': [1,2]
'blah2': 5
}
toBeChanged = "blah2"
def foo():
print(my_variables['blah'])
def changeVariable():
my_variables[toBeChanged] = my_variables.get(toBeChanged,0) + 1
for time in range(5):
changeVariable()
This has the added advantage that if a user enters a variable that doesn't exist a default is chosen, and doesn't override any variables that might be important for future execution.

Finding a value of a list

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
}

Get key in groovy maps

def map = [name:"Gromit", likes:"cheese", id:1234]
I would like to access map in such a way that I can get the key
something like the output should be
map.keys returns array of string. basically i just want to get the keys
output:
name
likes
id
try map.keySet()
and if you want an array:
map.keySet() as String[]; // thx #tim_yates
Or, more groovy-ish:
map.each{
key, value -> print key;
}
Warning: In Jenkins, the groovy-ish example is subtly broken, as it depends on an iterator. Iterators aren't safe in Jenkins Pipeline code unless wrapped in a #NonCPS function.
def map = [name:"Gromit", likes:"cheese", id:1234]
println map*.key
In groovy * is use for iterate all

Resources