Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Groovy noob here.

I have this map

signedMap = [[k:a, v:1], [k:b, v:-2], [k:c, v:3], [k:d, v:-4]]

I need to find the maximum absolute value, in this example -4

This my current code

def absMap = []

signedMap.each {
absMap.add([k:it.k, absv:it.v.abs()])
}
def sortedAbs = absMap.sort{it.absv}
def maxAbs = sortedAbs.last().absv

Is there a more elegant way to do this?

Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
259 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you are only intersted in the value, you could directly transform and find the maxium (instead of building a map, sorting, taking last).

signedMap.collect{ it.v.abs() }.max()

edit

To get the map for k and v you can also use max with a closure.

signedMap.max{ it.v.abs() }

It will give you the original v (so the negative -4).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...