背景
前端需要展示echarts图,本人需要修改一下返回数据格式。数据库查出来的为对象集合,类似这样
{
“sysName”: “”,
“equipType”: “”,
“num”: “”
}
首先需要将集合中name重复而其他不重复的数据归为一类。
fromVoList为对象集合
HashMap<String, List<EquipmentSysFromSuperVo>> hashMap = new HashMap<>();
List<EquipmentSysFromSuperVo> superVos = new ArrayList<>();
fromVoList.forEach(vo->{
EquipmentSysFromSuperVo superVo = new EquipmentSysFromSuperVo();
superVo.setEquipType(vo.getEquipType());
superVo.setNum(vo.getNum());
superVos.add(superVo);
putValue(vo.getSysName(),superVo,hashMap);
});
/**
* key相同,继续插入不同value
*/
public static void putValue(String key, EquipmentSysFromSuperVo str, HashMap<String, List<EquipmentSysFromSuperVo>> map){
List<EquipmentSysFromSuperVo> list = map.get(key);
if(list == null) {
list = new ArrayList();
}
for (EquipmentSysFromSuperVo equipmentSysFromSuperVo : list) {
if (equipmentSysFromSuperVo.equals(str)) {
return;
}
}
list.add(str);
map.put(key, list);
}
到这里我们的hashmap就变成我们想要的形状,可以进行排序了。
实操
首先,我们知道是没法直接对一个map进行排序的。这里可以想想有没其他的简便的方法。在集合工具类Collections中的sort可对集合进行排序,还可传入一个比较器按比较器进行排序。方法如下:
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T> void sort(List<T> list, Comparator<? super T> c) {
list.sort(c);
}
这样是不是一个list的话,像上面一样传一个Comparator,用Collections.sort()方法就能解决,但这是map,那能不能转为list呢?:
//todo 排序
ArrayList<Map.Entry<String, List<EquipmentSysFromSuperVo>>> entries = new ArrayList<>(hashMap.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, List<EquipmentSysFromSuperVo>>>() {
@Override
public int compare(Map.Entry<String, List<EquipmentSysFromSuperVo>> o1, Map.Entry<String, List<EquipmentSysFromSuperVo>> o2) {
Optional<String> count1 = o1.getValue().stream().map(EquipmentSysFromSuperVo::getNum).reduce((a, b) -> String.valueOf(Integer.parseInt(a) + Integer.parseInt(b)));
Optional<String> count2 = o2.getValue().stream().map(EquipmentSysFromSuperVo::getNum).reduce((a, b) -> String.valueOf(Integer.parseInt(a) + Integer.parseInt(b)));
return Integer.parseInt(count1.get()) - Integer.parseInt(count2.get());
}
});
// 不使用lambda友好点,可进内部类调试
// Collections.sort(entries, (o1, o2) -> {
// Optional<String> count1 = o1.getValue().stream().map(EquipmentSysFromSuperVo::getNum).reduce((a, b) -> String.valueOf(Integer.parseInt(a) + Integer.parseInt(b)));
// Optional<String> count2 = o2.getValue().stream().map(EquipmentSysFromSuperVo::getNum).reduce((a, b) -> String.valueOf(Integer.parseInt(a) + Integer.parseInt(b)));
// return Integer.parseInt(count1.get()) - Integer.parseInt(count2.get());
// });
最后return那count2-count1就是进行倒排序,反过来就是正排序