# LeetCode – Moving Average from Data Stream (Java)

Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.

Java Solution

This problem is solved by using a queue.

 public class MovingAverage { LinkedList queue; int size; double avg;   /** Initialize your data structure here. */ public MovingAverage(int size) { this.queue = new LinkedList(); this.size = size; }   public double next(int val) { if(queue.size()
Category >> Algorithms
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code>
String foo = "bar";
</code></pre>
• Ankit Shah

Much more simpler version:

public class MovingAverageInSlidingWIndow {
int windowsize;
Queue queue;
int sum;

public MovingAverageInSlidingWIndow(int windowsize) {
this.windowsize = windowsize;
this.sum = 0;
}

// finds moving average after inserting item n into data stream
private double findMovingAverage(int n) {
if (queue.size() > windowsize - 1) {
sum = sum - queue.poll();
}
queue.offer(n);
sum = sum + n;
return (double) sum / queue.size();
}

public static void main(String[] args) {

int windowsize = 3;
MovingAverageInSlidingWIndow m = new MovingAverageInSlidingWIndow(windowsize);

for (int i = 1; i < 20; i++) {
System.out.println("After Adding " + i + " to the queue: {" + m.queue.toString() + "}; Average is: " + m.findMovingAverage(i));

}
}
}

• Ameya Naik

We can simply persist the current sum of elements in queue in global variable. Thus, reducing the computation in next() method.

public class MovingAverage {
int size;
int sum = 0; // holds sum the queue

/** Initialize your data structure here. */
public MovingAverage(int size) {