java实现将list中对象的省市区个数和名称统计成 List<Map<String,List<Map<String,List<Map<String,Object>>>>>>结构
时间: 2023-11-11 22:47:02 浏览: 86
JAVA集合(List,Set,Map)
5星 · 资源好评率100%
可以使用Java的Stream流和Map集合来实现将List中对象的省市区个数和名称统计成List<Map<String,List<Map<String,List<Map<String,Object>>>>>>结构。下面是一个示例代码:
```java
import java.util.*;
import java.util.stream.Collectors;
public class ListToNestedMapExample {
public static void main(String[] args) {
// 假设有一个包含省市区信息的对象列表
List<Address> addressList = Arrays.asList(
new Address("省1", "市1", "区1"),
new Address("省1", "市1", "区2"),
new Address("省1", "市2", "区3"),
new Address("省2", "市3", "区4"),
new Address("省2", "市3", "区5")
);
// 使用Stream流和Collectors工具类进行统计
List<Map<String, List<Map<String, List<Map<String, Object>>>>>>> result = addressList.stream()
.collect(Collectors.groupingBy(Address::getProvince,
Collectors.groupingBy(Address::getCity,
Collectors.groupingBy(Address::getDistrict))))
.entrySet().stream()
.map(provinceEntry -> {
Map<String, List<Map<String, List<Map<String, Object>>>>> provinceMap = new HashMap<>();
provinceMap.put(provinceEntry.getKey(), provinceEntry.getValue().entrySet().stream()
.map(cityEntry -> {
Map<String, List<Map<String, Object>>> cityMap = new HashMap<>();
cityMap.put(cityEntry.getKey(), cityEntry.getValue().entrySet().stream()
.map(districtEntry -> {
Map<String, Object> districtMap = new HashMap<>();
districtMap.put("name", districtEntry.getKey());
districtMap.put("count", districtEntry.getValue().size());
return districtMap;
})
.collect(Collectors.toList()));
return cityMap;
})
.collect(Collectors.toList()));
return provinceMap;
})
.collect(Collectors.toList());
// 输出结果
for (Map<String, List<Map<String, List<Map<String, Object>>>>> provinceMap : result) {
for (Map.Entry<String, List<Map<String, List<Map<String, Object>>>>> provinceEntry : provinceMap.entrySet()) {
System.out.println(provinceEntry.getKey() + ":");
for (Map<String, List<Map<String, Object>>> cityMap : provinceEntry.getValue()) {
for (Map.Entry<String, List<Map<String, Object>>> cityEntry : cityMap.entrySet()) {
System.out.println("\t" + cityEntry.getKey() + ":");
for (Map<String, Object> districtMap : cityEntry.getValue()) {
System.out.println("\t\t" + districtMap.get("name") + " - count: " + districtMap.get("count"));
}
}
}
}
}
}
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;
}
}
}
```
这段代码会将对象列表中的省市区信息按照指定的结构统计并输出。你可以根据需要对结果进行进一步处理或使用。
阅读全文