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

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

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]

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)

How can I access the original map after wrapping it with ObservableMap?

I've created a map and then wrapped it as an ObservableMap. Later on, I try to access the original, unwrapped map, but I can't seem to access it. It seems to come back null.
private def _swarms = [:]
private def swarms = new ObservableMap(_swarms)
...
def orig = swarms.content // returns null
orig = swarms.mapDelegate // returns null
I don't see anything else at http://groovy.codehaus.org/api/groovy/util/ObservableMap.html that looks promising.
We cannot refer the property as a field in case of a Map interface. It will try to look for a key with that name and would return null if key<->value pair is absent. Try this instead:
def _swarms = [ a : 1 ]
def swarms = new ObservableMap( _swarms )
assert swarms.getContent() == [ a : 1 ]
assert swarms.getMapDelegate() == [ a : 1 ]
// Similar anomaly
assert !swarms.class
assert swarms.getClass().simpleName == "ObservableMap"
Similarly, you cannot use .class on Map. Instead getClass() has to be used.

How to find in a collection?

i have the following variable and collection
def currentProduct = "ITEM1"
def currentPresentation = "Crema"
def curentMeasure = "1ml"
def items = [[product:"ITEM1", presentation:"Crema", measure:"1ml", quantity:5, total:77.50], [product:"ITEM1", presentation:"Spray", measure:"Habracadabra", quantity:9, total:158.40]]
I need to get the quantity value in a map that its product, its presentation and its measure are equal to variable values, hopefully you can help me
Thanks for your time
Here You go:
items.find { it.product == currentProduct && it.presentation == currentPresentation && it.measure == curentMeasure}?.quantity
Another simpler approach will be as below:
def currentProductDetails = [
product:"ITEM1", presentation:"Crema", measure:"1ml"
]
items.find { !( currentProductDetails - it ) }?.quantity
// in case of multiple products
items.findAll { !( currentProductDetails - it ) }*.quantity
You can tailor currentProductDetails with whichever key value pair you have in hand for the current product instead of maintaining each variable separately.
Above logic is inspired from this question which is explained in details in this blog.
Dispite good #Opal's answer i will list here some additional possibilities:
Passing partial item map
If your item is [product:"ITEM1", presentation:"Crema", measure:"1ml", quantity:5, total:77.50]
and you want to search by some specified values of item, you can just pass submap of the item.
e.g.
def item = [product:currentProduct, presentation:currentPresentation, measure:curentMeasure]
def firstQuantity = items.find {it.subMap(item.keySet())==item}.quantity
That way allows you to be independent of item's keys.
Searching all quantities and suming them
Maybe in some cases you would like to have some of found quantities. You need then to use findAll() method.
def all = items.findAll { it.product == currentProduct && it.presentation == currentPresentation && it.measure == curentMeasure}.quantity.sum()
Use grep :
items.grep{it.product==currentProduct && it.presentation==currentPresentation && it.measure==curentMeasure}.collect{it.quantity}
FIDDLE

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