1、前端显示数据的格式
2.后台通过查询计算得到的数据
3.补全缺失的月份,值赋0就可以
4.代码
实体:
/**
* @author Mr. Dong
* @create 2021/11/23 13:22
* @desc list 对象属性相同的合并
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DataTrans{
private String name;
private double value;
}
工具类:
/**
* @author Mr. Dong
* @create 2021/11/24 11:18
* @desc 补全月份并赋值为0
**/
public class SupplementDateUtil {
public static final String[] monthAndDay = new String[]{"01","02","03","04","05","06","07","08","09","10","11","12"};
public static List<DataTrans> supplementDate(List<DataTrans> params){
List<DataTrans> list = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
//当前年份
int year = calendar.get(Calendar.YEAR);
for (DataTrans data:params){
list.add(data);
for (String s:monthAndDay){
DataTrans dataTrans = new DataTrans();
String date = year+"-"+s;
if (!date.equals(data.getName())){
dataTrans.setName(date);
dataTrans.setValue(0);
list.add(dataTrans);
}
}
}
// 集合中相同属性去重、值合并
return RemovalData.merge(list);
}
public static void main(String[] args) {
DataTrans dataTrans = new DataTrans("2021-08",0.05);
DataTrans dataTrans1 = new DataTrans("2021-05",0.8);
DataTrans dataTrans2 = new DataTrans("2021-05",0.8);
DataTrans dataTrans3 = new DataTrans("2021-11",0.86);
List<DataTrans> list = new ArrayList<>();
list.add(dataTrans);
list.add(dataTrans1);
list.add(dataTrans2);
list.add(dataTrans3);
List<DataTrans> list1 = supplementDate(list);
//根据月份升序排序
Collections.sort(list1, Comparator.comparing(DataTrans::getName,(t1, t2) -> t1.compareTo(t2)));
System.out.println(list1);
}
}
去重合并属性值工具类
mport com.cust.bigdatacollection.entity.DataTrans;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Mr. Dong
* @create 2021/11/23 11:21
* @desc list中相同的对象属性合并
**/
public class RemovalData {
public static List<DataTrans> merge(List<DataTrans> list) {
List<DataTrans> result = list.stream()
// 表示name为key,接着如果有重复的,那么从DataTrans对象o1与o2中筛选出一个,这里选择o1,
// 并把name重复,需要将value与o1进行合并的o2, 赋值给o1,最后返回o1
.collect(Collectors.toMap(DataTrans::getName, a -> a, (o1, o2)-> {
o1.setValue(o1.getValue() + o2.getValue());
return o1;
})).values().stream().collect(Collectors.toList());
return result;
}
}
5.结果