【发布时间】:2019-08-13 02:18:07
【问题描述】:
我想得到像 { "key1" : 4 ,"key2" :2 }
这样的结果我知道我可以使用 map 和 groupby 等
list.stream()
.map(map -> map2Entity(map))
.collect(Collectors.groupingBy(Entity::getKey,Collectors.summarizingInt(Entity::getCnt)) )
这是我的代码以及如何实现 (todo) 代码
public void test() {
List<Map<String, Object>> list = Arrays.asList(
createNewMap("key1", 1),
createNewMap("key2", 2),
createNewMap("key1", 3)
);
// i want get result like {"key1":4,"key2":2}
// how can i get the result don't use map()
list.stream()
.collect(Collectors.groupingBy(this::getKey),....(todo));
}
private String getKey(Map<String,Object> map){
return (String) map.get("key");
}
private Map<String, Object> createNewMap(String key, Integer val) {
Map<String, Object> map = new HashMap<>();
map.put("key", key);
map.put(key, val);
return map;
}
【问题讨论】:
-
我认为您的
createNewMap方法中的这一行map.put("key", key);是错误的。它的目的是什么?
标签: java lambda java-8 java-stream collectors