文章来源:https://gitee.com/wustrive/codes/l1typxfn79adhs0czmwb313
public void testStreamGroupBy() {
List<Map<String, Object>> items = Lists.newArrayList();
Map<String, Object> map = Maps.newHashMap();
map.put("daily", "2018-01-10");
map.put("count", 20);
items.add(map);
map = Maps.newHashMap();
map.put("daily", "2018-01-11");
map.put("count", 80);
items.add(map);
map = Maps.newHashMap();
map.put("daily", "2018-01-12");
map.put("count", 21);
items.add(map);
map = Maps.newHashMap();
map.put("daily", "2018-01-10");
map.put("count", 28);
items.add(map);
final List<Map<String, Object>> newItems = Lists.newArrayList();
//方式一: 使用遍历
for (int i = 0; i < result.size(); i++) {
Map<String, Object> oldMap = result.get(i);
boolean isContain = false;
for (int j = 0; j < newList.size(); j++) {
Map<String, Object> newMap = newList.get(j);
if (newMap.get("daily").equals(oldMap.get("daily"))) {
for (String key : oldMap.keySet()) {
newMap.put(key, oldMap.get(key));
oldMap.put("count", (int) newMap.get("count") + (int) oldMap.get("count"));
}
isContain = true;
break;
}
}
if (!isContain) {
newItems .add(oldMap);
}
}
System.out.println("方式一:" + newItems );
//方式二:使用1.8 stream流
Map<Object, Integer> sum = items.stream().collect(Collectors.groupingBy(m -> m.get("daily"), Collectors.summingInt(p -> ConvertUtil.obj2Int(p.get("count")))));
sum.forEach((k, v) -> {
newItems.add(ImmutableMap.of("daily", String.valueOf(k), "count", String.valueOf(v)));
});
System.out.println("方式二:"+newItems);
}