what are the different ways to create an Arraylist and Hashmap in groovy - 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

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]]

sub-classing a peewee field type to add behavior

I am trying to add the required behavior to a CharFiled or TextField so I can store a list of lists and retrieve it as a list of lists again. I am not asking for a solution rather I would like to see an example where a subclassing of an already supported field type is done as I didn't find any in the documentation or the Internet.
Do I have to do it as explained in the documents for creating a custom type?
for example:
class mylistoflists(TextField):
if yes, then what do I have to assign to field_type?
Example code (see tests/fields.py for full example):
class ListField(TextField):
def db_value(self, value):
return ','.join(value) if value else ''
def python_value(self, value):
return value.split(',') if value else []
class Todo(TestModel):
content = TextField()
tags = ListField()
class TestCustomField(ModelTestCase):
requires = [Todo]
def test_custom_field(self):
t1 = Todo.create(content='t1', tags=['t1-a', 't1-b'])
t2 = Todo.create(content='t2', tags=[])
t1_db = Todo.get(Todo.id == t1.id)
self.assertEqual(t1_db.tags, ['t1-a', 't1-b'])
t2_db = Todo.get(Todo.id == t2.id)
self.assertEqual(t2_db.tags, [])
t1_db = Todo.get(Todo.tags == Value(['t1-a', 't1-b'], unpack=False))
self.assertEqual(t1_db.id, t1.id)

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() ]
}

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>

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
}

Resources