I have an agent-based simulation where I have a collection called collection_dailyInfection
which has the numbers of new infections that arise on a daily basis. The collection looks a bit like this:
I'm now trying to write a function that adds up the total number of infections on any particular day. For example: on Day 6- total infections = 0+3+3+6+1 = 13.
The syntax for calculating the sum is:
double sum( collection, value )
- Returns the sum of values in the given collection.
For my particular example, this would be double sum( collection_dailyInfection, *value*)
, but I'm not sure what I should put in the 'value' argument. Could some help me out please?
These functions (methods) provided by AnyLogic for calculating statistics on collections use a fairly advanced feature of Java: the functional programming stuff added in Java 8. So the required syntax is not at all obvious. The main help page (AnyLogic Help --> Parameters, Variables, Collections --> Collections --> Functions to collect statistics on a collection) has a link to the UtilitiesCollection
class where these methods are defined.
You have a collection collection_dailyInfection
of daily infection counts; let's assume you specified this in AnyLogic as being of collection class ArrayList
with elements class as int
, and you used a cyclic event to add the count each simulated day.
Your sum expression should therefore be
sum( collection_dailyInfection, c -> c.doubleValue())
The c
is just an arbitrary identifier for the current element that the sum is on (effectively this sum method is looping through your collection) and the ->
is a special Java 8 functional programming operator. When you specify type int
in AnyLogic for your collection contents, they are actually stored as Integer
objects which are object versions of the int
primitives. (See any Java textbook to understand this.)
Thus, each entry (Integer
object) has a method doubleValue
which returns the value of the integer as a double. (AnyLogic's sum
function needs the 'value' bit to be a double
; i.e., a real (floating point) number.)
(anupam691997's answer is a 'pure Java' solution ignoring the AnyLogic context.)