时间: 2021-01-07 02:38:41
标签:
javascript
Java数据聚合问题
public class Demo {public static void main(String[] args) throws IOException {
HashMap m1 = new HashMap<>();
m1.put("month","2020-06");
m1.put("plan_working_hours",272.5);
m1.put("month_total_working_hours",120);
m1.put("project_code","ToB-APP");
m1.put("this_years_total_working_hours",287);
m1.put("project_name","B端APP框架");
m1.put("total_working_hours",307);
HashMap m2 = new HashMap<>();
m2.put("month","2020-07");
m2.put("plan_working_hours",272.5);
m2.put("month_total_working_hours",93);
m2.put("project_code","ToB-APP");
m2.put("this_years_total_working_hours",287);
m2.put("project_name","B端APP框架");
m2.put("total_working_hours",307);
HashMap m3 = new HashMap<>();
m3.put("month","2020-11");
m3.put("plan_working_hours",104);
m3.put("month_total_working_hours",16);
m3.put("project_code","1001");
m3.put("this_years_total_working_hours",67);
m3.put("project_name","C端底座");
m3.put("total_working_hours",150);
HashMap m4 = new HashMap<>();
m4.put("month","2020-12");
m4.put("plan_working_hours",104);
m4.put("month_total_working_hours",51);
m4.put("project_code","1001");
m4.put("this_years_total_working_hours",67);
m4.put("project_name","C端底座");
m4.put("total_working_hours",150);
ArrayListmaps = new ArrayList<>();
maps.add(m1);
maps.add(m2);
maps.add(m3);
maps.add(m4);
//todo 做数据聚合(
// 将project_name值相同的数据中的month和month_total_working_hours聚合到一个list中
// 每个project_name只有一个map数据)
/**
* 格式如下
*
* {
* "monthList": ["2020-06":120 ,"2020-07":93]
* "plan_working_hours": 272.5,
* "project_code": "ToB-APP",
* "this_years_total_working_hours": 287,
* "project_name": "B端APP框架",
* "total_working_hours": 307
* },
*/
}
}
最佳答案
Map one = Maps.newHashMap();
one.put("one",1);
one.put("two",2);
Map two = Maps.newHashMap();
two.put("one",1);
two.put("two",2);
List> list = Lists.newArrayList();
list.add(one);
list.add(two);
Set keySet = one.keySet();
Map> result = list.stream().reduce(new HashMap<>(), (s, o) -> {
keySet.forEach(a -> {
if (s.containsKey(a)) {
List value = s.get(a);
value.add(o.get(a));
} else {
List value = Lists.newArrayList();
value.add(o.get(a));
s.put(a, value);
}
});
return s;
}, (s, o) -> s);
System.out.println(result);