Java集合多重分组—lambda表达式实现
一、问题
一个查询结果怎么实现嵌套结果集,每个省份展开有多个城市每个城市展开有多个区域?
二、代码示例
package lambda;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
/**
* @Description Java集合多重分组---lambda表达式实现
* @Author King
* @Date 2019/11/21 13:41
* @Version 1.0
**/
@RestController
@RequestMapping("group")
public class GroupController {
/**
* 国家对象
*/
@Data
@AllArgsConstructor
static class Country {
/**
* 省份ID
*/
Integer pid;
/**
* 省份名称
*/
String pname;
/**
* 城市ID
*/
Integer cid;
/**
* 城市名称
*/
String cname;
/**
* 地区ID
*/
Integer did;
/**
* 地区名称
*/
String dname;
}
/**
* 创建测试数据(实际数据是从数据库查询)
*/
private static List<Country> list = new ArrayList<>(10);
static {
list.add(new Country(1, "北京", 2, "北京市", 11, "通州区"));
list.add(new Country(1, "北京", 2, "北京市", 17, "密云区"));
list.add(new Country(1, "北京", 2, "北京市", 4, "西城区"));
list.add(new Country(1, "北京", 2, "北京市", 10, "东城区"));
list.add(new Country(1, "北京", 2, "北京市", 16, "房山区"));
list.add(new Country(2, "天津", 7, "天津市", 3, "宝坻区"));
list.add(new Country(2, "天津", 7, "天津市", 9, "河北区"));
list.add(new Country(2, "天津", 7, "天津市", 15, "南开区"));
list.add(new Country(5, "山东", 9, "青岛市", 13, "市北区"));
list.add(new Country(5, "山东", 9, "青岛市", 21, "市南区"));
list.add(new Country(5, "山东", 11, "潍坊市", 32, "奎文区"));
list.add(new Country(5, "山东", 15, null, 16, "弗雷尔卓德"));
list.add(new Country(11, null, 15, "罗马市", 36, "德玛西亚区"));
}
@GetMapping("list")
public Map list() {
// 返回前端结果集
Map<String, Map<String, List<String>>> map = new HashMap<>(16);
// lambda进行多重分组
list.stream().collect(groupingBy(c -> {
// 因为groupingBy函数的参数不能为null 校验pname是否为空
String pname = c.getPname();
if (StringUtils.isBlank(pname)) {
pname = "其他";
}
return pname;
})).forEach((n, l) -> {
Map<String, List<String>> collect = l.stream()
.collect(groupingBy(c -> {
// 因为groupingBy函数的参数不能为null 校验cname是否为空
String cname = c.getCname();
if (StringUtils.isBlank(cname)) {
cname = "其他";
}
return cname;
}, mapping(Country::getDname, toList())));
map.put(n, collect);
});
return map;
}
}
三、测试
在浏览器中输入URL:http://localhost:8080/group/list
结果如下:
版权声明:本文为qq_39815207原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。