写一个省市级分组的例子,提供数据和输出结果
时间: 2024-03-01 19:50:56 浏览: 152
省市级联展示数据
好的,下面给出一个省市级分组的示例代码,包括数据和输出结果。
示例数据:
```java
List<Address> addressList = new ArrayList<>();
addressList.add(new Address("四川省", "成都市", "锦江区"));
addressList.add(new Address("四川省", "成都市", "武侯区"));
addressList.add(new Address("四川省", "绵阳市", "涪城区"));
addressList.add(new Address("四川省", "绵阳市", "游仙区"));
addressList.add(new Address("贵州省", "贵阳市", "南明区"));
addressList.add(new Address("贵州省", "贵阳市", "云岩区"));
addressList.add(new Address("贵州省", "遵义市", "红花岗区"));
addressList.add(new Address("贵州省", "遵义市", "汇川区"));
```
示例代码:
```java
public class GroupByDemo {
public static void main(String[] args) {
List<Address> addressList = new ArrayList<>();
addressList.add(new Address("四川省", "成都市", "锦江区"));
addressList.add(new Address("四川省", "成都市", "武侯区"));
addressList.add(new Address("四川省", "绵阳市", "涪城区"));
addressList.add(new Address("四川省", "绵阳市", "游仙区"));
addressList.add(new Address("贵州省", "贵阳市", "南明区"));
addressList.add(new Address("贵州省", "贵阳市", "云岩区"));
addressList.add(new Address("贵州省", "遵义市", "红花岗区"));
addressList.add(new Address("贵州省", "遵义市", "汇川区"));
Map<String, Map<String, List<Address>>> groupByProvinceCity = addressList.stream()
.collect(Collectors.groupingBy(Address::getProvince, Collectors.groupingBy(Address::getCity)));
groupByProvinceCity.forEach((province, cityMap) -> {
System.out.println(province + ":");
cityMap.forEach((city, addressList1) -> {
System.out.println("\t" + city + ":");
addressList1.forEach(address -> System.out.println("\t\t" + address.getDistrict()));
});
});
}
}
class Address {
private String province;
private String city;
private String district;
public Address(String province, String city, String district) {
this.province = province;
this.city = city;
this.district = district;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
}
```
输出结果:
```
四川省:
成都市:
锦江区
武侯区
绵阳市:
涪城区
游仙区
贵州省:
贵阳市:
南明区
云岩区
遵义市:
红花岗区
汇川区
```
以上代码中,使用Stream API对Address列表进行分组操作,首先按照省份进行分组,然后在每个省份内部按照城市进行分组。最后遍历分组后的结果,输出省、市、县区三级信息。
阅读全文