Is there a better way to find closest object with lesser marker?
class Prop implements Comparable {
BigDecimal marker
String value
int compareTo(other) {
return marker <=> other.marker
}
}
def props = [new Prop(marker: 0G, value: "1st"),
new Prop(marker: 20G, value: "2nd"),
new Prop(marker: 30G, value: "3rd"),
new Prop(marker: 40G, value: "4th"),
new Prop(marker: 50G, value: "5th"),
new Prop(marker: 100G, value: "6th"),
new Prop(marker: 1000G, value: "7th")]
def whereAmI = 44G
def here = props.findAll{it.marker <= whereAmI}.max()
Edit: Updated to return the correct object type, and nulls.
Assuming that order isn’t guaranteed, you could use the
injectmethod:If the list is always sorted, then simply use this:
The benefit here is you only loop over the set once, and you don’t create an additional interim
Listof lesser values.Now, depending on your list size, the argument may be that your original example is a lot easier to read, and a lot clearer. Clarity in code can trump performance.
(Note:
injectis Groovy’s version of reduce or fold.)