问题描述
油站银行流水计算:
以下是北京地区所有油站一天(片段)的收款流水记录:
要求:计算该天内每个油站的销售平均值?
代码
public static void main(String[] args) {
//初始化数据
StationFlow stationFlow1 = new StationFlow(1,"A10001",23.2);
StationFlow stationFlow2 = new StationFlow(2,"A10002",25.2);
StationFlow stationFlow3 = new StationFlow(3,"A10001",123.23);
StationFlow stationFlow4 = new StationFlow(4,"A10004",223.12);
StationFlow stationFlow5 = new StationFlow(5,"A10002",55.12);
StationFlow stationFlow6 = new StationFlow(6,"A10006",63.22);
StationFlow stationFlow7 = new StationFlow(7,"A10001",723.29);
StationFlow stationFlow8 = new StationFlow(8,"A10002",83.82);
StationFlow stationFlow9 = new StationFlow(9,"A10004",93.92);
StationFlow stationFlow10 = new StationFlow(10,"A10006",99.02);
StationFlow stationFlow11= new StationFlow(11,"A10011",123.88);
//将数据库填数据到list
List<StationFlow> list = new ArrayList<StationFlow>();
list.add(stationFlow1);list.add(stationFlow2);list.add(stationFlow3);list.add(stationFlow4);
list.add(stationFlow5);list.add(stationFlow6);list.add(stationFlow7);list.add(stationFlow8);
list.add(stationFlow9);list.add(stationFlow10);list.add(stationFlow11);
//计算每个油站平均值
//1 Map orderMap k=mmcode value=List<Double> 记录每次添加流水
HashMap<String, List<Double>> orderMap = new HashMap<String,List<Double>>();
//遍历原数据库,添加记录
for(StationFlow sf:list) {
//拿到油站编号和流水
String mmcode = sf.getMmcode();
double amount = sf.getAmuont();
//map.get(mmcode)==null 新纪录 否则旧纪录
List<Double> targetList = orderMap.get(mmcode);
if(orderMap.get(mmcode)==null) {
//添加新的记录放入mmcode 和 new amount放入list
List<Double> list2 = new ArrayList<Double>();
list2.add(amount);
orderMap.put(mmcode, list2);
}
//旧纪录,获得list,list.add添加记录
else {
targetList.add(amount);
orderMap.put(mmcode, targetList);
}
}
//2.计算平均值,初始化反参
Map<String, Double> map = new HashMap<String,Double>();
//遍历orderMap
for(Map.Entry<String, List<Double>>entry : orderMap.entrySet()) {
//获得mmcode
String mmcode = entry.getKey();
//获得每个油站的集合
List<Double> list2 = entry.getValue();
//遍历集合,计算累加值
double sumAmount=0.0;
for(Double d: list2) {
sumAmount=sumAmount+d;
}
//计算平均值=累加值/list.size()
double avgAmount=sumAmount/list2.size();
map.put(mmcode,avgAmount);
}
//检查
for(Map.Entry<String, Double> entry : map.entrySet()) {
System.out.println(entry.getKey() + "-" + entry.getValue());
}
}