java实现将list中对象的省市区统计成 List<Map<String,List<Map<String,Object>>>>结构
时间: 2023-11-11 18:47:02 浏览: 104
可以使用Java的流操作和集合操作来实现将List中的对象的省市区统计成List<Map<String, List<Map<String, Object>>>>结构。下面是一个可能的实现示例:
```java
import java.util.*;
import java.util.stream.Collectors;
public class ListConverter {
public static List<Map<String, List<Map<String, Object>>>> convertList(List<Address> addresses) {
// 使用流操作将地址列表按省份进行分组
Map<String, List<Address>> provinceMap = addresses.stream()
.collect(Collectors.groupingBy(Address::getProvince));
// 构建结果列表
List<Map<String, List<Map<String, Object>>>> resultList = new ArrayList<>();
// 遍历省份列表
for (Map.Entry<String, List<Address>> provinceEntry : provinceMap.entrySet()) {
String province = provinceEntry.getKey();
List<Address> provinceAddresses = provinceEntry.getValue();
// 使用流操作将省份下的地址按城市进行分组
Map<String, List<Address>> cityMap = provinceAddresses.stream()
.collect(Collectors.groupingBy(Address::getCity));
// 构建省份的结果Map
Map<String, List<Map<String, Object>>> provinceResult = new HashMap<>();
resultList.add(provinceResult);
// 遍历城市列表
for (Map.Entry<String, List<Address>> cityEntry : cityMap.entrySet()) {
String city = cityEntry.getKey();
List<Address> cityAddresses = cityEntry.getValue();
// 构建城市的结果Map
List<Map<String, Object>> cityResult = new ArrayList<>();
provinceResult.put(city, cityResult);
// 遍历区域列表
for (Address address : cityAddresses) {
// 构建区域的结果Map
Map<String, Object> districtResult = new HashMap<>();
districtResult.put("district", address.getDistrict());
cityResult.add(districtResult);
}
}
}
return resultList;
}
public static void main(String[] args) {
// 测试数据
List<Address> addresses = new ArrayList<>();
addresses.add(new Address("江苏省", "南京市", "鼓楼区"));
addresses.add(new Address("江苏省", "南京市", "玄武区"));
addresses.add(new Address("江苏省", "苏州市", "姑苏区"));
addresses.add(new Address("浙江省", "杭州市", "西湖区"));
List<Map<String, List<Map<String, Object>>>> result = convertList(addresses);
System.out.println(result);
}
// 地址类,包含省份、城市和区域信息
static 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 String getCity() {
return city;
}
public String getDistrict() {
return district;
}
}
}
```
运行上述示例代码,将会输出统计结果的列表。每个元素都是一个省份的结果Map,其中每个键值对表示一个城市和对应的区域列表。注意,示例代码中使用了静态内部类Address来表示地址信息,你可以根据实际需求替换为自己的对象类型。
阅读全文