```java
class AreaResource {
/**
* area表示的是地区全路径,最多可能有5级,用分隔符连接,分隔符是 spliter,
* 例如分隔符是逗号 则area型如 中国,重庆,江津 中国,重庆,合川 中国,重庆,梁平
* count表示数量
*/
String area;
String spliter;
long count;
}
现在需要把 List<AreaResource> 进行字符串转换,供下游处理,需要做到同级能合并
比如 area为中国,四川,成都 有15个门店, 中国,重庆,合川 有12个门店 中国,重庆,涪陵有33个门店
spliter为逗号 "," 最终转化成JSON的形式,并且同级的地域需要被合并,最终生成的JSON字符串如下所示
{"中国":{"四川":{"成都":15]},"重庆":{"合川 ":12,"涪陵":33}}}
/*
请完善下面的类
*/
public interface ProvinceService {
String getFormattedJSONByResource(List<AreaResource> areas);
}
```java
可以做,前缀树算法,很好实现的,需要源码的话要稍等一下~
先汇总数据,再把数据按要求格式是输出
1.转化成json格式这步不难,难点在数据汇总上
2.数据的格式A,B,C,数量,是树形结构,当ABC某一个相同时,划归为一类
3.问题变成了树形结构数据分类汇总,使用map去做比较合适了
暴力拼装
List<AreaResource> list = new ArrayList<>();
AreaResource a = new AreaResource("中国,四川,成都",",",15);
AreaResource b = new AreaResource("中国,重庆,合川,永川",",",12);
AreaResource c = new AreaResource("中国,重庆,涪陵",",",33);
list.add(a);
list.add(b);
list.add(c);
System.out.println(list);
Map<String, Long> collect = list.stream().collect(Collectors.toMap(k -> {
String[] split = k.getArea().split(k.getSpliter());
return split[split.length-1];
},
v -> v.getCount()
));
// System.out.println(collect);
Map<String,Object> map = new HashMap<>();
list.forEach( v -> {
String area = v.getArea();
String[] split = area.split(v.getSpliter());
for (int i=0;i<split.length;i++) {
String name = split[i];
Object o = map.get(name);
if(o != null){ continue; }
if(i>0) o = map;
int index = 0;
while (index<i){
o = ((Map)o).get(split[index++]);
}
if(o == null ){
Map<String , Object> obj = new HashMap<>();
map.put(name,obj);
continue;
}
if(o instanceof Map){
if(collect.containsKey(name)){
((Map)o).put(name,collect.get(name));
}else{
if(!((Map)o).containsKey(name)){
((Map)o).put(name,new HashMap<>());
}
}
}
}
});
System.out.println(JSON.toJSONString(map));