# Moving Average from Data Stream

{% embed url="<https://www.lintcode.com/problem/642/>" %}

## Solution 1 (Java)

```java
public class MovingAverage {

    Queue<Integer> q;
    double sum;
    int size;

    /*
    * @param size: An integer
    */
    public MovingAverage(int size) {
        q = new ArrayDeque<>();
        sum = 0;
        this.size = size;
    }

    /*
     * @param val: An integer
     * @return:  
     */
    public double next(int val) {
        sum += val;
        if (q.size() == size) {
            int pollVal = q.poll();
            sum -= pollVal;
        }
        q.offer(val);
        return sum / q.size();
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.yushunchen.com/algo/queue-and-stack/moving-average-from-data-stream.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
