常见的生成树结构都是使用递归来进行操作,今天学到一个新方法,使用Map来生成。
实体类:
package collection.tree;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/*** @Author gao
* @Date 2023/11/15 14:43
*/
@Data
public class Gis {
private Long id;
private String name;
private Long parentId;
private Gis parent;
private List<Gis> children=new ArrayList<>();
public Gis(Long id, String name, Long parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
}
public class TestGis {
private static List<Gis> gisList=new ArrayList<Gis>(){{
this.add(new Gis(1l,"北京",null));
this.add(new Gis(12l,"北京2",1l));
this.add(new Gis(2l,"吉林",null));
this.add(new Gis(21l,"长春",2l));
this.add(new Gis(22l,"四平",2l));
}};
public static void main(String args[]){
List<Gis> result=new ArrayList();
Map<Long,Gis> gisMap=new HashMap();
for (Gis gis : gisList){
gisMap.put(gis.getId(),gis);
}
for (Gis gis : gisList){
Long parentId=gis.getParentId();
if (ObjectUtil.isNotEmpty(parentId)){
gisMap.get(parentId).getChildren().add(gis);
}else{
result.add(gis);
}
}
//一般给前端传数据都是放到List中,这里直接输出result就ok了
//此处使用递归方法,把Map中的树转换成List
List<Gis> listResult=new ArrayList<>();
gisTreeFormatList(result,listResult);
System.out.println(listResult);
}
public static void gisTreeFormatList(List<Gis> listGis,List result){
for (Gis gis:listGis){
result.add(gis);
if (ObjectUtil.isNotEmpty(gis.getChildren())){
gisTreeFormatList(gis.getChildren(),result);
}
}
}
}