实体类:
public class Entry {
private Integer id;
private String fullName;
private String levelName;
private Integer level;
public Entry(Integer id, String fullName, String levelName, Integer level) {
this.id = id;
this.fullName = fullName;
this.levelName = levelName;
this.level = level;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getLevelName() {
return levelName;
}
public void setLevelName(String levelName) {
this.levelName = levelName;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
}
Main主方法:
import com.alibaba.fastjson.JSONObject;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map> map = new HashMap<>();
String firstKey = null;
for (Entry test : testList()) {
if (test.getLevel() == 1){
firstKey = test.getLevelName();
System.out.println(firstKey+"===========");
List list = new ArrayList<>();
map.put(test.getLevelName(),list);
}else {
String key = test.getLevelName().substring(0,test.getLevelName().lastIndexOf('.'));
if (map.containsKey(key)){
map.get(key).add(test);
}else {
List list = new ArrayList<>();
list.add(test);
map.put(key,list);
}
}
}
Map result = new HashMap<>();
result.put(firstKey, cycle(map,firstKey));
System.out.println(JSONObject.toJSONString(result));
}
private static List cycle(Map> map, String key){
if (map.containsKey(key)){
List list = new ArrayList();
map.get(key).forEach(entry->{
List testResult = cycle(map, entry.getLevelName());
if (testResult == null){
list.add(entry.getFullName());
}else {
Map map1 = new HashMap();
map1.put(entry.getFullName(),testResult);
list.add(map1);
}
});
return list;
}
return null;
}
static private List testList(){
List list = new ArrayList<>();
list.add(new Entry(1, "1_xxx", "1", 1));
list.add(new Entry(2, "1.1_xxx", "1.1", 2));
list.add(new Entry(3, "1.2_xxx", "1.2", 2));
list.add(new Entry(4, "1.3_xxx", "1.3", 2));
list.add(new Entry(5, "1.1.1_xxx", "1.1.1", 3));
list.add(new Entry(6, "1.1.2_xx", "1.1.2", 3));
list.add(new Entry(7, "1.2.1_xxx", "1.2.1", 3));
list.add(new Entry(8, "1.3.1_xxx", "1.3.1", 3));
list.add(new Entry(9, "1.3.2_xxx", "1.3.2", 3));
list.add(new Entry(10, "1.1.1.1_xxx", "1.1.1.1", 4));
list.add(new Entry(11, "2_xxx", "2", 1));
list.add(new Entry(12, "2.1_xxx", "2.1", 2));
list.add(new Entry(13, "2.2_xxx", "2.2", 2));
list.add(new Entry(14, "2.3_xxx", "2.3", 2));
list.add(new Entry(15, "2.1.1_xxx", "2.1.1", 3));
list.add(new Entry(16, "2.1.2_xx", "2.1.2", 3));
list.add(new Entry(17, "2.2.1_xxx", "2.2.1", 3));
list.add(new Entry(18, "2.3.1_xxx", "2.3.1", 3));
list.add(new Entry(19, "2.3.2_xxx", "2.3.2", 3));
list.add(new Entry(20, "2.1.1.1_xxx", "2.1.1.1", 4));
return list;
}
}