Sort values of a Map in Groovy - groovy

I have a map where a key holds multiple values
datamap = [ 'Antenna Software':[ 'Salarpuria', 'Cessna', 'Vrindavan Tech', 'Alpha Center' ],
'Ellucian':[ 'Malvern', 'Ellucian House', 'Residency Road'] ]
here i need to alphabetically sort the values
datamap = [ 'Antenna Software':[ 'Alpha Center', 'Cessna', 'Salarpuria', 'Vrindavan Tech' ],
'Ellucian':[ 'Ellucian House', 'Malvern', 'Residency Road' ] ]
how to do it in groovy way?

You should be able to do:
def sortedMap = datamap.sort().collectEntries { k, v ->
[ k, v.sort( false ) ]
}
If you're not bothered about sorting the keys of the map, you can get rid of the initial sort():
def sortedMap = datamap.collectEntries { k, v ->
[ k, v.sort( false ) ]
}
Explanation of sort( false ):
By default, the sort method in Groovy changes the original list, so:
// Given a List
def a = [ 3, 1, 2 ]
// We can sort it
def b = a.sort()
// And the result is sorted
assert b == [ 1, 2, 3 ]
// BUT the original list has changed too!
assert a != [ 3, 1, 2 ] && a == [ 1, 2, 3 ]
So if you pass false to sort, it leaves the original list alone, and just returns the sorted list:
// Given a List
def a = [ 3, 1, 2 ]
// We can sort it (passing false)
def b = a.sort( false )
// And the result is sorted
assert b == [ 1, 2, 3 ]
// AND the original list has remained the same
assert a == [ 3, 1, 2 ]

Related

How to extend an existing list with values of a dictionary as a string?

How to extend an existing list with values of a dictionary as a string in below Python codes?
x = [ 'h1', 'h2' ]
y = [ 'h3', 'h4' ]
dict_sample = {'xyz': ['ab', 'bc'], 'mno': ['cd', 'de']}
x.extend(dict_sample.keys()) ---> (Output) ['h1', 'h2', 'xyz', 'mno']
y.extend(dict_sample.values()) ----> (Output) ['h3', 'h4', ['ab', 'bc'], ['cd', 'de']]
However, how to obtain the below desired output for second case?
['h3', 'h4', '['ab', 'bc']', '['cd', 'de']']
Assuming the desired output looks like ['h3', 'h4', '["ab", "bc"]', '["cd", "de"]'],
which includes stringified json elements, here's a way to do it:
import json
y = [ 'h3', 'h4' ]
dict_sample = {'xyz': ['ab', 'bc'], 'mno': ['cd', 'de']}
y.extend([json.dumps(e) for e in dict_sample.values()])
print(y)

Add key value with index as value in every dict in a list

I have a json file with list of dicts. I want to modify its content by adding key:value in every dict with index as the value
Note that the json file is malform, so I need to remove the extra '[]'
file.json
[
{
"sample1": 1,
"sample2": "value"
}
[]
{
"sampleb": "123",
"some": "some"
}
...............
]
code
""" open the files"""
with open("list1.json", "r") as f:
data = f.read()
data = data.replace("][", ",")
data = json.loads(data)
for v in data:
for i, c in v.items():
c["rank"] = i + 1
""" put back to file"""
with open("list1.json", "w") as file:
file.write(data)
So what I am trying to achieve is something like
[
{
"rank": 1
"sample1": 1,
"sample2": "value"
},
{
"rank": 2,
"sampleb": "123",
"some": "some"
}
...............
]
But I got error
c["rank"] = i
TypeError: 'str' object does not support item assignment
printing the index print 1 shows
0,
1,
.....
0,
1,
........
0,
1
But it should be
0,
1,
2,
3,
4
5
...
100
Any ideas?

Groovy: Confusion about Map Reassign via `getOrDefault`

I'm going to initialize a empty Map dynamically in a loop, i.e. key1 and key2 are variables in the loop:
Map<String, Map<String, List>> map = [
key1: [
key2: []
]
]
I'm trying initialize the map structure by getOrDefault in two ways. One (y) using the hardcode as key name, another (x) using the variable as the keyname:
Map y = [:]
Map x = [:]
String b = 'b'
String c = 'c'
y = y.getOrDefault( "b" , [ "b" : [:] ] )
.getOrDefault( "c" , [ "b" : [ "c" : []] ] )
x = x.getOrDefault( "${b}" , [ "${b}" : [:] ] )
.getOrDefault( "${c}" , [ "${b}" : [ "${c}" : []] ] )
However, when I try get result of map.b.c,
Map x:
x.get("${b}").get("${c}") : works
x["${b}"]["${c}"] : java.lang.NullPointerException
Map y works well in all various ways
println """
y['b']['c'] : ${y['b']['c']}
y.b.c : ${y.b.c}
y.get('b').get('c') : ${y.get('b').get('c')}
x.get("\${b}") : ${x.get("${b}")}
x["\${b}"] : ${x["${b}"]} // *why null*
x.get("\${b}").get("\${c}") : ${x.get("${b}").get("${c}")}
"""
println """ x["\${b}"]["\${c}"] : ${x["${b}"]["${c}"]} """
==> result
y['b']['c'] : []
y.b.c : []
y.get('b').get('c') : []
x.get("${b}") : [c:[]]
x["${b}"] : null // *why null*
x.get("${b}").get("${c}") : []
Exception thrown
java.lang.NullPointerException: Cannot get property 'c' on null object
at ConsoleScript77.run(ConsoleScript77:21)
I want to know why x.get("${b}").get("${c}") works, but x["${b}"]["${c}"] got null
btw, here the dynamic map initialization details:
Map m = [
'x' : [
'name': 'x',
'size': ['1', '2'],
'age': '1',
],
'y': [
'name': 'x',
'size': ['2', '3'],
'age': '2'
]
]
Map a = [:]
m.each{ k, v ->
v.size.each {
String t = "${v.name}-${it}"
a = a.getOrDefault(t, ["${t}": [:]])
println """
t: ${t}
k: ${k}
a: ${a}
a.t: ${a.t}
a.get("${t}"): ${a.get("${t}")}
a["${t}"]: ${a["${t}"]}
"""
}
}
=== output:
t: x-1
k: x
a: [x-1:[:]]
a.t: null
a.get("x-1"): [:]
a["x-1"]: null
t: x-2
k: x
a: [x-2:[:]]
a.t: null
a.get("x-2"): [:]
a["x-2"]: null
....
Appreciate #daggett.
So the truth is:
y.each { k, v ->
println """
key: ${k} \t\t\t key.getClass(): ${k.getClass()}
value: ${v} \t\t value.getClass(): ${v.getClass()}
"""
}
x.each { k, v ->
println """
key: ${k} \t\t\t key.getClass(): ${k.getClass()}
value: ${v} \t\t value.getClass(): ${v.getClass()}
"""
}
==> result
key: b key.getClass(): class java.lang.String
value: [c:[]] value.getClass(): class java.util.LinkedHashMap
key: b key.getClass(): class org.codehaus.groovy.runtime.GStringImpl
value: [c:[]] value.getClass(): class java.util.LinkedHashMap
So, according to my previous ${x["${b}"]}, the key of x ( "${b}" ) was type conversion to String, and x only has the key belongs to GStringImpl, so the result is null
However, .get("${b}") works, because of :
println "${b}".getClass() // class org.codehaus.groovy.runtime.GStringImpl
Here more details:
Map x = [:]
String str = 'a'
x = x.getOrDefault( "${str}", [ "${str}" : [:] ] )
x.each { k, v -> println "${k}: ${k.getClass()}" }
Map x = [:]
String str = 'a'
x = x.getOrDefault( "${str}", [ "${str}" : [:] ] )
x.each { k, v -> println "${k}: ${k.getClass()}" } // a: class org.codehaus.groovy.runtime.GStringImpl
assert x == [ "${s}" : [:] ]
assert x.a == null
assert x."${str}" == null
assert x["${str}"] == null
assert x[str] == null
assert x.get(str) == null
assert x.get("${str}") == [:]

what is the difference between findResults and collect in groovy?

Here is the code using collect
​def lst = [1,2,3,4];
def newlst = [];
newlst = lst.collect {element -> return element * element}
println(newlst);
Here is the code using findResults
def lst2 = [1,2,3,4];
def newlst2 = [];
newlst2 = lst2.findResults {element -> return element * element}
println(newlst2);
​Both seem to return [1, 4, 9, 16] so what is the difference? Thanks!
Basically the difference is how they deal with null values
collect when sees null will collect it, while findResults won't pick it.
In other words, the size of resulting collection is the same as the size of input when using collect.
Of course you could filter out the results but its an additional step
Here is a link to the example I've found in the internet
Example:
​def list = [1, 2, 3, 4]
println list.coll​​​​​​​​​​​​​​ect { it % 2 ? it : null}
// [1, null, 3, null]
println list.findResults { it % 2 ? it : null}​
// [1,3]
When we need to check if returned list is empty then findResults seem more useful. Thanks to Mark for the answer.
def list = [1, 2, 3, 4]
def l1 = list.collect { it % 100 == 0 ? it : null}
def l2 = list.findResults { it % 100 == 0 ? it : null}
if(l1){
println("not null/empty " + l1)
}
if(l2){
println("not null/empty " + l2)
}
​

How do I implement a comparator for a map in Groovy?

I have a map in Groovy:
['keyOfInterest' : 1, 'otherKey': 2]
There is a list containing a number of these maps. I want to know if a map exists in the list with keyOfInterest of a certain value.
If the data types were simple objects, I could use indexOf(), but I don't know how to do this with a more complicated type. E.g. (taken from the docs)
assert ['a', 'b', 'c', 'd', 'c'].indexOf('z') == -1 // 'z' is not in the list
I'd like to do something like:
def mapA = ['keyOfInterest' : 1, 'otherKey': 2]
def mapB = ['keyOfInterest' : 3, 'otherKey': 2]
def searchMap = ['keyOfInterest' : 1, 'otherKey': 5]
def list = [mapA, mapB]
assert list.indexOf(searchMap) == 0 // keyOfInterest == 1 for both mapA and searchMap
Is there a way to do this with more complicated objects, such as a map, easily?
While #dmahapatro is correct, and you can use find() to find the map in the list of maps that has the matching index... that's not what you asked for. So I'll show how you can get either the index of that entry in the list, or just whether a map with matching keyOfInterest exists.
def mapA = ['keyOfInterest' : 1, 'otherKey': 2]
def mapB = ['keyOfInterest' : 3, 'otherKey': 2]
def searchMap = ['keyOfInterest':1, 'otherKey': 55 ]
def list = [mapA, mapB]
// findIndexOf() returns the first index of the map that matches in the list, or -1 if none match
assert list.findIndexOf { it.keyOfInterest == searchMap.keyOfInterest } == 0
assert list.findIndexOf { it.keyOfInterest == 33 } == -1
// any() returns a boolean OR of all the closure results for each entry in the list.
assert list.any { it.keyOfInterest == searchMap.keyOfInterest } == true
assert list.any { it.keyOfInterest == 33 } == false
Note that there is no performance penalty for using one over the other as they all stop as soon as one match is found. find() gives you the most information, but if you're actually looking for the index or a boolean result, these others can also be used.
Simplest implementation would be to use find(). It returns null when criteria is not met in the supplied closure.
def mapA = ['keyOfInterest' : 1, 'otherKey': 2]
def mapB = ['keyOfInterest' : 3, 'otherKey': 2]
def list = [mapA, mapB]
assert list.find { it.keyOfInterest == 1 } == ['keyOfInterest':1, 'otherKey':2]
assert !list.find { it.keyOfInterest == 7 }

Resources