arraysvelocityvtlapache-velocity

How to get the maximum value in an array in Velocity Template Language (VTL)


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


Solution

  • 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