1

Using Velocity Template Language (VTL), I would like to get the maximum value of an array. I was looking quite a while through the documentation of Apache Velocity but couldn't find a method for doing this.

Here is my sample array:

#set($array = [2,4,12,3,1,4,34,8])
$sorter.sort($array)

In this example, I would like to get 34

SteffPoint
  • 479
  • 2
  • 9
  • 24

1 Answers1

2

Sorting the array is a bit overkill if you only need the maximum value.

I you have access to the Velocity context, the best option is to have a Java tool do it for you.

If you don't have access to the context, or just want a quick and dirty solution, you can do something like:

#set($max = -10000)
#foreach($val in $array)
  #set($max = $math.max($max,$val))
#end

which requires the org.apache.velocity.tools.generic.MathTool to be present in the context. And if that's not the case, you can still simply do something like:

#set($max = -10000)
#foreach($val in $array)
  #if($val > $max)
    #set($max = $math.max($max,$val))
  #end
#end
Claude Brisson
  • 4,085
  • 1
  • 22
  • 30
  • Thanks Claude. The Math-Tool is fortunately available in my context. Thanks for the way more professional solution :) – SteffPoint Mar 11 '20 at 09:12
  • 1
    You're welcome. As a side node, being one of the maintainers of Velocity, I duly noted that it would be cool to have a MathTool.max(Collection) method... – Claude Brisson Mar 12 '20 at 10:31