1.首先,可以很轻松的从后台数据库获取多个list。list如下:
2.根据其中一个的list的排序,获取出x轴的数组。(echarts,highcharts的X,Y轴一般为数组)
Java代码:
String x[] = new String[list.size()];
int y[] = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
Map map = (Map) list.get(i);
x[i] = "" + map.get("KFYQ");
y[i] = Integer.parseInt("" + map.get("SUM"));
}
3.关键是第二个,第三个的排序要对应第一个已经排好序的数组。这里利用了map的一个containsKey方法。
3.1把原来的List<Map>转变成Map.
Map mapList1 = new LinkedHashMap();
for (int i = 0; i < list1.size(); i++) {
Map map = (Map) list1.get(i);
mapList1.put(map.get("KFYQ"), map.get("SUM"));
}
3.2 用了map的containsKey使之与排好序的第一个X轴的值对应。
int y1[] = new int[list.size()];
for (int i = 0; i < x.length; i++) {
if(mapList1.containsKey(x[i])){
y1[i] = Integer.parseInt(""+mapList1.get(x[i]));
}else {
y1[i] = 0;
}
}
4.转成json,前台解析
5.效果图
-------------------------------------------------------------------------------------------------------------------------------------------------------
完整Java代码:
public String getSQFB() throws Exception {
Map mapAll = new HashMap();
//获取三区数量的List<Map>
List list = testMapper.getSQFB();
List list1 = testMapper.getSQFB1();
List list2 = testMapper.getSQFB2();
//hightcharts需要的数据格式
String x[] = new String[list.size()];
int y[] = new int[list.size()];
int y1[] = new int[list.size()];
int y2[] = new int[list.size()];
//确定x轴的顺序
for (int i = 0; i < list.size(); i++) {
Map map = (Map) list.get(i);
x[i] = "" + map.get("KFYQ");
y[i] = Integer.parseInt("" + map.get("SUM"));
}
//把原来的List<Map>转变成Map。key为X轴的值,value为Y轴值。
Map mapList1 = new LinkedHashMap();
for (int i = 0; i < list1.size(); i++) {
Map map = (Map) list1.get(i);
mapList1.put(map.get("KFYQ"), map.get("SUM"));
}
//用containsKey使之与排好序的第一个X轴的值对应。
for (int i = 0; i < x.length; i++) {
if (mapList1.containsKey(x[i])) {
y1[i] = Integer.parseInt("" + mapList1.get(x[i]));
} else {
y1[i] = 0;
}
}
//同上
Map mapList2 = new LinkedHashMap();
for (int i = 0; i < list2.size(); i++) {
Map map = (Map) list2.get(i);
mapList2.put(map.get("KFYQ"), map.get("SUM"));
}
for (int i = 0; i < x.length; i++) {
if (mapList2.containsKey(x[i])) {
y2[i] = Integer.parseInt("" + mapList2.get(x[i]));
} else {
y2[i] = 0;
}
}
mapAll.put("x", x);
mapAll.put("y", y);
mapAll.put("y1", y1);
mapAll.put("y2", y2);
Gson gson = new Gson();
return gson.toJson(mapAll);
}