今天遇到一个问题如下:
Paste_Image.png Paste_Image.png把上图的数据结构,转换成下图的数据结构。结果今天脑袋瓦特了,想了有2个小时没用想出思路。后来在网友的帮助下得到解决。
回到正题:
这是原始的数据结构:
Arera
@Data
public class Area implements Serializable {
private String prvoince;
private String city;
private String district;
private String address;
public Area(String prvoince, String city, String district, String address) {
this.prvoince = prvoince;
this.city = city;
this.district = district;
this.address = address;
}
}
下面是需要的辅助类
City:
@Data
public class City implements Serializable {
private String cityName;
private List<District> districtList;
public void addDistrict(List<District> district) {
for (District d : district) {
districtList.add(d);
}
}
public City(String cityName, List<District> districtList) {
this.cityName = cityName;
this.districtList = districtList;
}
}
Distract:
@Data
public class District implements Serializable{
private String districtName;
private List<Detail> detailList;
public void addDetail(List<Detail> detail) {
for (Detail d : detail) {
detailList.add(d);
}
}
public District(String districtName, List<Detail> detailList) {
this.districtName = districtName;
this.detailList = detailList;
}
}
Detail:
@Data
public class Detail implements Serializable {
private String address;
public Detail(String address) {
this.address = address;
}
}
下面就是开始转换数据结构的代码了,其实很简单。
public static void main(String[] args) {
List<Area> areaList = new ArrayList<Area>();
areaList.add(new Area("江苏省", "南京市", "玄武区", "新模范马路1001号"));
areaList.add(new Area("江苏省", "南京市", "秦淮区", "雨花台路30号"));
areaList.add(new Area("江苏省", "南京市", "鼓楼区", "中山1路1号"));
areaList.add(new Area("湖南省", "长沙市", "芙蓉区", "橘子洲"));
areaList.add(new Area("湖南省", "长沙市", "下沙区", "宝昌路32号"));
areaList.add(new Area("江苏省", "徐州市", "云龙区", "云龙大道22号"));
areaList.add(new Area("江苏省", "徐州市", "铜山区", "上海路45号"));
covertData(areaList);
}
private static void covertData(List<Area> areaList) {
Map<String, City> cityMap = new HashMap<>(); //最终需要的数据结构
Map<String, District> districtMap = new HashMap<>(); //区名称的数据结构, 辅助作用
areaList.stream().forEach(item -> {
Detail detail = new Detail(item.getAddress());
List<Detail> details = new ArrayList<>();
details.add(detail);
if (districtMap.containsKey(item.getDistrict())) {
//如果区名称已经存在,更新区下面的详细地址
districtMap.get(item.getDistrict()).addDetail(details);
} else {
//如果区名称不存在,就创建这个区并且加入map
District district = new District(item.getDistrict(), details);
List<District> districtList = new ArrayList<>();
districtList.add(district);
districtMap.put(item.getDistrict(), district);
if (cityMap.containsKey(item.getCity())) {
//如果city存在,更新city下面的区
cityMap.get(item.getCity()).addDistrict(districtList);
} else {
//如果city名称不存在,就创建这个city并加入map
City city = new City(item.getCity(), districtList);
cityMap.put(item.getCity(), city);
}
}
});
System.out.println(JSONObject.toJSONString(cityMap)); //这个就是我最终需要的结果
}
特此记一下,说不定哪天脑子又突然瓦特了。
网友评论