Sum of Array List In groovy - groovy

I have an Array List in groovy in below format. I want the sum of integer values in this list.
[ {"value":1}, {"value":1}, {"value":10}, {"value":11}, {"value":12}]
Expected Output
1+1+10+11+12=35

Oh it's very easy.
list.value.sum()

I would prefer using the Groovy Spread Operator.
The Spread Operator (*.) is used to invoke an action on all items of an aggregate object.
Specific to your question, the best way coding the desired result is:
list*.value.sum()
The difference is only a * but it is best practice to use the language correctly.

Related

Groovy List of List

I have a Camel app that returns records from a database. When I output the Camel ${body} I see:
[
{sku=HT-0001, Performance=Fair, ProductGroup=Movers, name=ProductPerformance},
{sku=HT-0002, Performance=Great for product group, ProductGroup=Staid, name=ProductPerformance},
{sku=VT-KK2150, Performance= act7, ProductGroup=Slammers, name=ProductPerformance}
]
I would like to build a data structure for those values in Groovy. I am assuming I am dealing with a list of lists given the structure displayed above. Not sure what other type of structure it might be.
Just looking for opinions as regards if this is indeed a list of lists and if so, how best to write sample Groovy code to represent those values.
I think I figured this out ...I believe Camel is returning a list of Maps and can be simulated locally as:
def y = [
['sku':'VT-KK2150', 'Performance':'act7', 'ProductGroup':'Jammers', 'name':'ProductPerformance1'],
['sku':'VT-LL2150', 'Performance':'act8', 'ProductGroup':'Sammers', 'name':'ProductPerformance2'],
['sku':'VT-MM2150', 'Performance':'act9', 'ProductGroup':'Bammers', 'name':'ProductPerformance3'],
]

using list values in an if statement to compare with a string

I have this list and string
list_var=(['4 3/4','6','6 3/4'])
string_var='there are 6 inches of cement inside'
i want to check through and find if any of the elements of the list is in the string
if list_var in strin_var (wont work of course due to the fact its a list but this is what i want to achieve is to compare all of the values and if any match return true)
i tried using any function but this not seem to work i would also like to achieve this without using loops as the code i will be using this in contains extracting data from a lot of files so execution speed is an issue
you will have to iteratre over the list at least once as you are trying a search operation.
is_found = any(True for i in list_var if i in string_var)
works perfectly for this scenario.

Looking up a list of words into a String in Scala

I need to find if any word from a word list (which could be a Set or List or another structure) is contained (as a sub-string) in another String and I need the best possible performance.
This could be an example:
val query = "update customer set id=rand() where id=1000000009;"
val wordList = Set("NOW(", "now(", "LOAD_FILE(", "load_file(", "UUID(", "uuid(", "UUID_SHORT(",
"uuid_short(", "USER(", "user(", "FOUND_ROWS(", "found_rows(", "SYSDATE(", "sysdate(", "GET_LOCK(", "get_lock(",
"IS_FREE_LOCK(", "is_free_lock(", "IS_USED_LOCK(", "is_used_lock(", "MASTER_POS_WAIT(", "master_pos_wait(",
"RAND(", "rand(", "RELEASE_LOCK(", "release_lock(", "SLEEP(", "sleep(", "VERSION(", "version(")
What is the best option to achieve the best performance? I have read about the contains method but it doesn't work for sub-strings. Is the only option to iterate through the list and to use the method indexOf or there is a better option?
For Scala collections, the method to use in order to answer a question like "is there an item in this collection that satisfies my condition?" is exists (scroll up slightly when you get there because the scaladoc pages are weird about linking directly to methods).
Your condition is "does the string (query) contain this item (word)?" For this, you can use String's contains method, which comes from Java.
Putting it together, you'll get
wordList.exists { word => query.contains(word) }
// or, with some syntax sugar
wordList exists { query.contains }
You can also use .find instead of .exists, which will return an Option containing the first match that was found, instead of just a Boolean indicating whether or not something was found.
scala> wordList.exists(query.contains)
res1: Boolean = true
scala> wordList.find(query.contains)
res2: Option[String] = Some(rand()
This is advice for solution:
Check that you need to optimize it. "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."
Array is collection with fastest access to element. Use it to increase access's speed.
Sometimes use a ParArray may increase performance.
If it's acceptable, for best performance first cast string to lower case, and remove all UPPER_CASE from set.
You can use own "contains" method to find any of substring. E.g., you can group some words by their prefixes (or suffixes) and don't pass all group if next (prev) symbol is different.
Use native Java to increase performance (Scala can wrap array)
First find all positions of (, because all variants related to it. Than you can check last word's symbol.
Sorry for my English. It is not best advice, but I know small amount of people (e.g. on acm.timus.ru) which can write more faster functions at Scala.

How to get the last KEY from a map in groovy?

I am trying to get the last KEY from this map in groovy. However, it seems like groovy doesn't have a method for returning the last key in the map.
def person = [fname: "john", sname: "smith", age: 25]
I have tried person.lastKey() and person.lastEntry() but these methods seems to be specific for java only.
You can use person.keySet()[-1]​ or person.keySet().last()​
And to get whole entry use entrySet() instead of keySet()
See the Groovy demo online
lastKey is part of the SortedMap interface and the Groovy map literal gives you an LinkedHashMap, which is the explanation, why your attempts failed.
Maps (the interface SortedMap inherits from) are on their own not ordered or sorted. So what you are asking here, will only work for ordered (which the Groovy map literal will give you) or sorted maps, so make sure you have one of those or you will see random elements instead of what you perceive as last. If order is important consider using a list of key-value-tuples instead.

SSRS - How to get a part of a string

I have a parameter called Analyst group in this format :
[Dimension].[Analyst Group].&[Nl.Workplace.Foundation]
I want to pass this parameter to another report, to filter data. Its a multi value parameter. But the other report only accepts it in this format : [KanBan].[Analyst Group].&[Nl.Workplace.Foundation]
So im trying to isolate the "Nl.Workplace.Foundation", so i can do the following thing in the Go To Report parameter expression :="[KanBan].[Analyst Group].&["& --Isolated analyst group-- &"]" to create the desired format.
So what i need is to extract the part between .&[ and ]
But i really have no idea how to isolate that part of the string.
Found a solution! If i just use the Parameter.label instead of Parameter.value it automatically does what i want!
A different solution has been found, but I will still answer the initial question. It could help.
So what i need is to extract the part between .&[ and ]
You could use a regex.
This may not be the fastest way but it can handle most of the situations.
So let's assume you have a string containing:
[Dimension].[Analyst Group].&[Nl.Workplace.Foundation]
And you want to get the following string:
Nl.Workplace.Foundation
Just use the following expression:
=System.Text.RegularExpressions.Regex.Match("[Dimension].[Analyst Group].&[Nl.Workplace.Foundation]", "\.&\[(?<NWF>[^]]+)\]").Groups("NWF").Value
In the expression, replace the input string with your dynamic values, like for example:
=System.Text.RegularExpressions.Regex.Match(Fields!Dimension.Value & "." & Fields!AnalystGroup.Value, "\.&\[(?<NWF>[^]]+)\]").Groups("NWF").Value
I'm keeping the formula as simple as possible so that you can easily adapt it, with, say, handling the case where an input string will not have a match (with the above query it will return #Error).
You could do this by adding an IIF() or better, use a custom function that you can reuse in several places and will reduce the length of your expression.

Resources