HDPCD-Java-複習筆記(10)-lab

Java lab booklet


Computing the Moving Average of a Stock

僅展示部分代碼,其餘參考前一個複習筆記。

Reducer recycle logic's data example

window size:3, Symbol:Apple, Values:1.26, 3, 4

Apple [1.26]

Apple [1.26, 3], Apple [3]

Apple [1.26, 3, 4], Apple [3,4], Apple [4]


public static class MovingAverageReducer extends
			Reducer<Stock, DoubleWritable, Text, DoubleWritable> {
		private Text outputKey = new Text();
		private DoubleWritable outputValue = new DoubleWritable();
		private static final int WINDOW_SIZE = 50;
		private LinkedList<StockWindow> windows = new LinkedList<StockWindow>();

		@Override
		protected void reduce(Stock key, Iterable<DoubleWritable> values,
				Context context) throws IOException, InterruptedException {
			StockWindow stockWindow;
			for (DoubleWritable value : values) {
				windows.add(new StockWindow(key.getSymbol()));
				for (StockWindow window : windows) {
					window.addPrice(value.get(), key.getDate());
				}
				if (windows.size() >= WINDOW_SIZE) {
					stockWindow = windows.removeFirst();
					outputKey.set(stockWindow.toString());
					outputValue.set(stockWindow.getAverage());
					context.write(outputKey, outputValue);
				}
			}
			windows.clear();

		}
	}

package average;

import java.util.LinkedList;

public class StockWindow {
	private String symbol;
	private String endDate;
	private LinkedList<Double> prices = new LinkedList<Double>();
	

	public StockWindow(String symbol) {
		super();
		this.symbol = symbol;
	}

	public String getSymbol() {
		return symbol;
	}

	public String getEndDate() {
		return endDate;
	}

	public void addPrice(double price, String endDate) {
		prices.add(price);
		this.endDate = endDate;
	}
	
	public double getAverage() {
		double sum = 0.0;
		int count = 0;
		for(double price: prices) {
			count++;
			sum += price;
		}
		return sum/count;
	}
	
	public String toString() {
		return symbol + "," + endDate;
	}
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章