Stephane Grenier
Stephane Grenier

Reputation: 15925

How to total a list of numbers in FreeMarker

I've been going through the documentation for FreeMarker and I can't find any examples of how to sum up a list of values in a list.

So let's say I have the following class, how do I add a line at the end to include the totals of values:

public class MyObject
{
    List<long> values
}

I can then view the individual items as explained in the list directive.

<#list MyObject.values as value>
  ${value}
</#list>

I can even find the documentation on how to do arithmetic on the individual values but how can I then add a new line to show the total of all the values? In other words I can't find any documentation on how to sum a list of numbers...

And also can you please include the link to the page in the documentation that explains how to do this. Thanks.

Upvotes: 1

Views: 8910

Answers (2)

Hack-R
Hack-R

Reputation: 23200

This is a custom function to do it. I just took the function to average a list of numbers and changed it slightly.

<#function mysum nums...>
  <#local sum = 0>
  <#list nums as num>
    <#local sum += num>
  </#list>
  <#if nums?size != 0>
    <#return sum>
  </#if>
</#function>
${mysum(10, 20)}
30

This is where I got the original function for averaging a list: http://freemarker.org/docs/ref_directive_function.html (see Example 2)

Upvotes: 2

castletheperson
castletheperson

Reputation: 33486

If you're using Java 8, there are built-in functions for finding the sum of a List<Long>. If you convert the List to a Stream to a LongStream, you can use .sum():

${MyObject.values.stream().mapToLong(Long::longValue).sum()}

You can see this at work in this question for example.

Upvotes: 1

Related Questions