Map<String, Map<String, Double>> statisticsMap = new HashMap<>();
for (DosingStatistics statistics : dosingStatisticsList) { String key = statistics.getPlantName() + "," + statistics.getMedicamentName(); // 初始化统计数据 if (!statisticsMap.containsKey(key)) { statisticsMap.put(key, new HashMap<>()); } //先获取日期,再分割 String date = new SimpleDateFormat("yyyy-MM-dd").format(statistics.getDate()); //日期按-分隔 String[] split = date.split("-"); //年 String y = split[0]; //月 String m = split[1]; //日 String d = split[2]; String newDate = null; if (Long.valueOf(d) < 27 ){ //并且月份小月12,若等于12,年份加1 //若日小于27号,则,保留年月,若大约27号,则年不动,月份加一(保证月份是1-12月) newDate = y + "-" + m; }else { //大于27号,则月份加一 String newMonth = m+1; //若月份小月等于12,则保留原来的和 if (Long.valueOf(newMonth) <= 12){ newDate = y + "-" + newMonth; }else { //若大于12 String newYear = y + 1; newDate = newYear + "-" + 1; } } // 更新统计数据 Map<String, Double> monthStatistics = statisticsMap.get(key); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM"); Date filtrationDate = dateFormat.parse(newDate); String boundaryDateString = filtrationDate.toString(); if (!monthStatistics.containsKey(boundaryDateString)) { if (statistics.getCumulativeAddition() != null){ monthStatistics.put(boundaryDateString, statistics.getCumulativeAddition()); }else { monthStatistics.put(boundaryDateString, Double.valueOf(0)); } } else { Double previousAddition = monthStatistics.get(boundaryDateString); if (statistics.getCumulativeAddition() != null){ monthStatistics.put(boundaryDateString, previousAddition + statistics.getCumulativeAddition()); }else{ monthStatistics.put(boundaryDateString, previousAddition + Double.valueOf(0)); } } }
for (Map.Entry<String, Map<String, Double>> entry : statisticsMap.entrySet()) { String[] keyParts = entry.getKey().split(","); //装置名称 String plantName = keyParts[0]; //物料名称 String medicamentName = keyParts[1]; Map<String, Double> monthStatistics = entry.getValue(); for (Map.Entry<String, Double> monthEntry : monthStatistics.entrySet()) { //时间 String dateString = monthEntry.getKey(); //添加量 Double cumulativeAddition = monthEntry.getValue(); try { Date firstDayOfMonth = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH).parse(dateString); result.add(new DosingStatistics(plantName, medicamentName, firstDayOfMonth, cumulativeAddition)); } catch (ParseException e) { e.printStackTrace(); } } }