ID | 省 | 市 | 区 |
---|
1 | 广东省 | 深圳市 | 宝安区 | 2 | 广东省 | 广州市 | 天河区 | 3 | 广东省 | 广州市 | 从化区 | 4 | 浙江省 | 杭州市 | 西湖区 |
例如从数据库中获取这种格式数据,然后要转成树结构
无需多重遍历,时间复杂度O(n),用map来存放每个key的索引位置,然后根据key在树List中找到对应的层级,进行添加数据。 附上代码:
public class TestDemo {
public static void main(String[] args) {
Address address = new Address();
address.setProvince("广东省");
address.setCity("深圳市");
address.setZone("宝安区");
Address address2 = new Address();
address2.setProvince("广东省");
address2.setCity("广州市");
address2.setZone("天河区");
Address address3 = new Address();
address3.setProvince("广东省");
address3.setCity("广州市");
address3.setZone("从化区");
Address address4 = new Address();
address4.setProvince("浙江省");
address4.setCity("杭州市");
address4.setZone("西湖区");
List<Address> addressList = Arrays.asList(address, address2, address3, address4);
List<AdressTree> treeList = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
addressList.forEach(v->{
String province = v.getProvince();
Integer provinceIndex = map.get(province);
if (provinceIndex == null) {
AdressTree tree = new AdressTree(province, province);
treeList.add(tree);
provinceIndex = treeList.size() - 1;
map.put(province, provinceIndex);
}
String city = v.getCity();
String cityKey = province + "_" + city;
Integer cityIndex = map.get(cityKey);
if (cityIndex == null) {
List<AdressTree> children = treeList.get(provinceIndex).getChildren();
AdressTree tree = new AdressTree(cityKey, city);
children.add(tree);
cityIndex = children.size() - 1;
map.put(cityKey, cityIndex);
}
String zone = v.getZone();
String zoneKey = cityKey + "_" + zone;
Integer zoneIndex = map.get(zoneKey);
if (zoneIndex == null) {
List<AdressTree> children = treeList.get(provinceIndex).getChildren().get(cityIndex).getChildren();
AdressTree tree = new AdressTree(zoneKey, zone);
children.add(tree);
zoneIndex = children.size() - 1;
map.put(zoneKey, zoneIndex);
}
});
System.out.println(JSONArray.toJSONString(treeList));
}
}
@Data
class Address {
private String province;
private String city;
private String zone;
}
@Data
class AdressTree {
private String key;
private String title;
private List<AdressTree> children = new ArrayList<>();
public AdressTree(String key, String title) {
this.key = key;
this.title = title;
}
}
|