利用 Collectors.groupingBy分组,简单实用,上demo
public static void main(String[] args) {
List<ProArea> infoVOS = Lists.newArrayList();
ProArea sd = new ProArea("山东", "济南", "县城1");
ProArea sd1 = new ProArea("山东", "济南", "县城2");
ProArea yt = new ProArea("山东", "烟台", "县城3");
ProArea cs = new ProArea("湖南", "长沙", "县城4");
ProArea xt = new ProArea("湖南", "湘潭", "县城5");
ProArea xt2 = new ProArea("湖南", "湘潭", "县城6");
infoVOS.add(sd);
infoVOS.add(sd1);
infoVOS.add(yt);
infoVOS.add(cs);
infoVOS.add(xt);
infoVOS.add(xt2);
Map<String, Map<String, List<ProArea>>> infoMap = infoVOS.stream()
.collect(Collectors.groupingBy(ProArea::getPro, Collectors.groupingBy(ProArea::getAre)));
System.out.println(JSON.toJSONString(infoMap));
}
@Data
static class ProArea {
private String pro;//省份
private String are;//地市
private String pre;//县
public ProArea(String pro, String are, String pre) {
this.pro = pro;
this.are = are;
this.pre = pre;
}
}
输出的JSON:
{
"山东": {
"济南": [
{
"are": "济南",
"pre": "县城1",
"pro": "山东"
},
{
"are": "济南",
"pre": "县城2",
"pro": "山东"
}
],
"烟台": [
{
"are": "烟台",
"pre": "县城3",
"pro": "山东"
}
]
},
"湖南": {
"湘潭": [
{
"are": "湘潭",
"pre": "县城5",
"pro": "湖南"
},
{
"are": "湘潭",
"pre": "县城6",
"pro": "湖南"
}
],
"长沙": [
{
"are": "长沙",
"pre": "县城4",
"pro": "湖南"
}
]
}
}
评论里说报错,但没说报什么错。我想大概是因为不知道代码中用到的技术Jar包,附加如下:
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.Data;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;