Get the values of maps in arrayList - groovy

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>

Related

creating a list of object in 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]]

map built from string value extraction - cannot recover value

I'm currently trying to manipulate a map in groovy but I'm facing a problem that I can't work out.
I build a map in order to have an id as key and a name as value
I have to store it as a string, then recover it and rebuild the map.
My keys look like id:my:device, names look like
When I build my map, I end up having something like
mymap = [id:my:device: ...etc.] which does not cause any problem for recovery, mymap[id:my:device] gives my device name.
EDIT :
I build the map doing name_uid_map[measure.uid] =jSonResponse.value for every map element and, at the end of my testCase, I store it doing testRunner.testCase.setPropertyValue("name_uid_map", name_uid_map.toString()
After storage and recovery, as it is stored as a string, it becomes uneasy to decypher. I modify the string in order to have "id:my:device"='my device name', then I rebuild the map doing the following (otherwise it splits from the first ':')
mymap = map.split(",\\s*").collectEntries{
def keyAndVal = it.split("=")
[(keyAndVal[0]):keyAndVal[1]]
}
The problem is now my rebuilt map looks like
{"id:my:device"='my device name' ... }
If I do
mymap.each{
key, value ->
log.info key
log.info value
}
I obtain
key : "id:my:device"
value : my device name
which is correct. When I want to recover value from the key, I encounter my problem, ie:
mymap["id:my:device"] = null
If I try to get the type of the value I get :
my value = class org.codehaus.groovy.runtime.NullObject
I'm not easy at all with handling maps in groovy and I'm sure I've done something wrong, but I can't figure it out, could someone help me ?
Alex
Well,
Actually I found another way to fulfill my needs
In the testStep where I build my initial map I do the following:
import groovy.json.JsonBuilder
and I store my map in a custom property like this, to make sure it's a valid JSON
testRunner.testCase.setPropertyValue("name_uid_map", new JsonBuilder(name_uid_map).toString())
In the next testStep, I do the following (simple extraction of JSON):
def name_uid_map = context.expand( '${#TestCase#name_uid_map}' )
def jsonSlurper = new groovy.json.JsonSlurper()
map = jsonSlurper.parseText(name_uid_map)
and it works fine.

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
}

what are the different ways to create an Arraylist and Hashmap in groovy

I have created an ArrayList like the following:
def list = new ArrayList()
But the codenarc report it is warning like following.
ArrayList objects are better instantiated using the form "[] as ArrayList"
What are the better ways to instantiate the collections?
You can do:
def list = [] // Default is ArrayList
def list = [] as ArrayList
ArrayList list = []
And again, for HashMap:
HashMap map = [:]
def map = [:] as HashMap
The default in this case is a LinkedHashMap:
def map = [:]
Typical is:
def list = []
other options include
def list = new ArrayList()
def list = new ArrayList<Foo>()
List list = new ArrayList()
def list = [] as ArrayList
List list = [] as ArrayList
and of course:
List<Foo> list = new ArrayList<Foo>();
Similar options exist for HashMap using [:].
But the codenarc report it is warning like following.
ArrayList objects are better instantiated using the form "[] as ArrayList"
IMO, this is bad advice on Codenarc's part as it assumes that the implementation type of [] is ArrayList. This is true today, but may not always be.
The simplest/best/usual way to create a List implementation is:
def list = []
If possible, I will usually write something like
List<String> list = []
Just to make it a bit more obvious what this list should contain, i.e. for the sake of code readability. If I wanted to create a specific type of list I would instantiate a List "the Java way"
List<String> list = new SomeCustomListImplementation<String>()
But in practice I can't remember ever doing this.
Why don't you just use a suggestion from codenarc?
def list = [] as ArrayList

Resources