一、问题
一个查询结果怎么实现嵌套结果集,每个省份展开有多个城市每个城市展开有多个区域?

二、代码示例
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;
@RestController
@RequestMapping("group")
public class GroupController {
@Data
@AllArgsConstructor
static class Country {
Integer pid;
String pname;
Integer cid;
String cname;
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);
list.stream().collect(groupingBy(c -> {
String pname = c.getPname();
if (StringUtils.isBlank(pname)) {
pname = "其他";
}
return pname;
})).forEach((n, l) -> {
Map<String, List<String>> collect = l.stream()
.collect(groupingBy(c -> {
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
结果如下:
