# Golang 实现Map Reduce Filter **Published by:** [Robin](https://paragraph.com/@robin-8/) **Published on:** 2023-02-26 **URL:** https://paragraph.com/@robin-8/golang-map-reduce-filter ## Content package main import ( "fmt" "strconv" ) // map reduce filter and pippline func itemsFilter(items []map[string]string, f func(map[string]string) bool) []map[string]string { newSlice := make([]map[string]string, 0) for _, item := range items { if f(item) { newSlice = append(newSlice, item) } } fmt.Println("itemsFilter result: ", newSlice) return newSlice } func mapToString(items []map[string]string, f func(map[string]string) string) []string { newSlice := make([]string, 0) for _, item := range items { newSlice = append(newSlice, f(item)) } fmt.Println("mapToString resutl: ", newSlice) return newSlice } func fieldSum(items []string, f func(string) int) int { var sum int for _, item := range items { sum += f(item) } return sum } func main() { var users = []map[string]string{ { "name": "张三", "age": "18", }, { "name": "李四", "age": "22", }, { "name": "王五", "age": "20", }, { "name": "赵六", "age": "-10", }, { "name": "孙七", "age": "60", }, { "name": "周八", "age": "10", }, } validUsers := itemsFilter(users, func(user map[string]string) bool { age, ok := user["age"] if !ok { return false } intAge, err := strconv.Atoi(age) if err != nil { return false } if intAge < 18 || intAge > 35 { return false } return true }) ageSlice := mapToString(validUsers, func(user map[string]string) string { return user["age"] }) sum := fieldSum(ageSlice, func(age string) int { intAge, _ := strconv.Atoi(age) return intAge }) fmt.Printf("用户年龄累加结果: %d\n", sum) } ## Publication Information - [Robin](https://paragraph.com/@robin-8/): Publication homepage - [All Posts](https://paragraph.com/@robin-8/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@robin-8): Subscribe to updates