HDPCD-Java-复习笔记(10)-lab

来源:互联网 发布:ubuntu超级用户权限 编辑:程序博客网 时间:2024/06/14 04:55

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 extendsReducer<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>();@Overrideprotected 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;}}




原创粉丝点击