Java, Go 实现map针对某个字段进行group by

其实这个问题可以简化成实现 wordcount 功能。

一、Java案例,对数组字符实现 wordcount:

String[] a = {"a","b","c","d","a","b","a","c","e"};
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < arrays.length; i++) {
if (map.get(arrays[i]) != null) {
map.put(arrays[i], map.get(arrays[i]) + 1);
} else {
map.put(arrays[i], 1);
}
}
Set<String> keys = map.keySet();
for (String key: keys) {
Integer value = map.get(key);
System.out.println("元素" + key + " " + value);
}

二、Go案例,需要对 Slice里面的 UID字段进行word count,然后把word count写入到对应的ExtInfo字段

 


type MyStruct struct {
UID int
ExtInfo map[string]int
}
var slice = []*MyStruct{
{
UID: 1,
ExtInfo: make(map[string]int),
},
{
UID: 1,
ExtInfo: make(map[string]int),
},
{
UID: 2,
ExtInfo: make(map[string]int),
},
{
UID: 1,
ExtInfo: make(map[string]int),
},
}

 

 

 1、word count,参考Java案例实现的word count原理

map1 := make(map[int]int)
for _, v := range slice {
if _, ok := map1[v.UID]; ok {
map1[v.UID] = map1[v.UID] + 1
} else {
map1[v.UID] = 1
}
}
fmt.Println(map1)

2、将 word count写入到对应的ExtInfo字段
map2 := make(map[int]*MyStruct)
for _, v := range slice {
if _, ok := map1[v.UID]; ok {
v.ExtInfo["count"] = map1[v.UID]
map2[v.UID] = v
}
}
fmt.Println(map2)


posted @ 2020-10-02 15:02  Rthena  阅读(1025)  评论(0编辑  收藏  举报