需求::前端根据后端的返回数据:画统计图;
1.动态获取地域数据以及数据中的平均值,按照平均值降序排序;
说明:
X轴是动态的,有对应区域数据则展示;
X轴 区域数据降序排序;
代码:
@Override
public List<Map<String,Object>> getTimeData(HttpServletRequest request, Map<String, Object> paramMap) {
List<Map<String,Object>> list = getCountData(request,paramMap);
list = list.stream().filter(e -> (e.get("status").equals("关闭"))).collect(Collectors.toList());
List<Map<String,Object>> resultList = new ArrayList<>();
String[] reginArr = {"安徽","安顺","北京","北美","长春","长沙","成都","承德","大连","武汉"};
int[] count = new int[reginArr.length];
double[] processTimeCount = new double[reginArr.length];
double[] processTimeAvg = new double[reginArr.length];
for (int i = 0; i < list.size(); i++) {
String processTime = String.valueOf(list.get(i).get("processTime"));
String region = String.valueOf(list.get(i).get("region")).trim();
if(!processTime.contains(".")){
list.get(i).put("processTime","0.0");
}
String processTime2 = String.valueOf(list.get(i).get("processTime"));
for (int j = 0; j < reginArr.length; j++) {
if(region.equals(reginArr[j].trim())){
count[j] = count[j] + 1; // 统计次数
processTimeCount[j] = processTimeCount[j] + Double.parseDouble(processTime2); // 统计合并值
}
}
}
// 计算平均值
for (int i = 0; i < processTimeCount.length; i++) {
processTimeAvg[i] = processTimeCount[i]/count[i];
// double类型的数据当分母的数值趋近0的时候,返回来的数值就是一个NAN:
if(Double.isNaN(processTimeAvg[i])){
processTimeAvg[i] = 0.0;
}
}
// 将数据封装集合
for (int i = 0; i < reginArr.length; i++) {
Map<String,Object> mapResult = new HashMap<>();
String avg = String.valueOf(processTimeAvg[i]);
mapResult.put("title",reginArr[i]);
mapResult.put("value",avg.substring(0,avg.indexOf(".") +2));
resultList.add(mapResult);
}
// 数据过滤
List<Map<String,Object>> finalList = new ArrayList<>();
// 过滤不需要的数据;
for (int i = 0; i < resultList.size(); i++) {
String value = String.valueOf(resultList.get(i).get("value"));
if(!value.equals("0.0")){
finalList.add(resultList.get(i));
}
}
// 排序后最终输出集合:
List<Map<String,Object>> finalList2= new ArrayList<>();
Double[] valueSort = new Double[finalList.size()];
String[] titleSort = new String[finalList.size()];
// 用数组存储需要排序的元素;
for (int i = 0; i < finalList.size(); i++) {
valueSort[i] = Double.parseDouble(String.valueOf(finalList.get(i).get("value")));
titleSort[i] = String.valueOf(finalList.get(i).get("title"));
}
// 多个数组排序;
BubblSortUtils.bubbleSortDescMultipleDouble(valueSort,titleSort);
// 根据排序结果封装List;
for (int i = 0; i < valueSort.length; i++) {
String ch = String.valueOf(titleSort[i]);
for (int j = 0; j < finalList.size(); j++) {
String value = String.valueOf(finalList.get(j).get("title"));
if(ch.equals(value)){
finalList2.add(finalList.get(j));
}
}
}
// 添加排序字段:sortValue
for (int i = 0; i < finalList2.size(); i++) {
finalList2.get(i).put("sortValue",i+1);
}
return finalList2;
}
Postman接口测试:
总结: 代码中有一个地域的数组:reginArr ,如果地域字典新增,还需维护这个字典,所以还是不够灵活;参考【Java 动态数据统计图】动态数据统计思路Demo(动态,排序)三(115)和【Java代码优化】for循环,多if条件分支代码优化一(110)中的优化方案二;有更灵活计算逻辑;