Program to find simple moving average | Java program to calculate Simple Moving Average ; queue used to store list so that we get the average ; constructor to initialize period ; function to add new data in the list and update the sum so that we get the new mean ; Updating size so that length of data set should be equal to period as a normal mean has ; function to calculate mean ; Driver code
import java . util . * ; public class SimpleMovingAverage { private final Queue < Double > Dataset = new LinkedList < Double > ( ) ; private final int period ; private double sum ; public SimpleMovingAverage ( int period ) { this . period = period ; } public void addData ( double num ) { sum += num ; Dataset . add ( num ) ; if ( Dataset . size ( ) > period ) { sum -= Dataset . remove ( ) ; } } public double getMean ( ) { return sum / period ; } public static void main ( String [ ] args ) { double [ ] input_data = { 1 , 3 , 5 , 6 , 8 , 12 , 18 , 21 , 22 , 25 } ; int per = 3 ; SimpleMovingAverage obj = new SimpleMovingAverage ( per ) ; for ( double x : input_data ) { obj . addData ( x ) ; System . out . println ( " New ▁ number ▁ added ▁ is ▁ " + x + " , ▁ SMA ▁ = ▁ " + obj . getMean ( ) ) ; } } }