树形基础类(如果要构造树形,需要继承此类,此处我创建TestVo类)
public class BasicTreeVo<T> {
private Long id ;
private String title ;
@JsonIgnore
private Long parentId ;
@JsonIgnore
private String parentName ;
private List<T> children = new ArrayList<>( );
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<T> getChildren() {
return children;
}
public void setChildren(List<T> children) {
this.children = children;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BasicTreeVo<?> that = (BasicTreeVo<?>) o;
return Objects.equals( id, that.id );
}
@Override
public int hashCode() {
return Objects.hash( id );
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
}
public class TestVo extends BasicTreeVo<TestVo>{
}
树形工具类
public class TreeUtils {
public static <T extends BasicTreeVo> List<T> getTree(List<T> sources){
List<T> rootList = getTreeRoot(sources);
int len = rootList.size();
for(int i=0;i<len;i++){
getTreeChildNode(sources,rootList.get( i ));
}
return rootList;
}
/**
* 分离出根节点
* @return
*/
private static <T extends BasicTreeVo> List<T> getTreeRoot(List<T> sources){
List<T> rootList = new ArrayList<>( );
for(int i=sources.size()-1;i>=0;i--){
if(sources.get( i ).getParentId()==null){
rootList.add( sources.remove( i ) );
}
}
return rootList;
}
/**
* 分离出子节点
* @return
*/
private static <T extends BasicTreeVo> void getTreeChildNode(List<T> sources,T parentNode){
T t = null;
for(int i=sources.size()-1;i>=0&i<sources.size();i--){
if(sources.get( i ).getParentId().equals(parentNode.getId())){
parentNode.getChildren().add(sources.get( i ));
t = sources.remove( i );
getTreeChildNode(sources,t);
}
}
}
}
测试类
public class TreeTest {
public static void main(String[] args) {
//测试数据样式,按照此数据格式封装数据,可快速构建树形代码
String str = "[{\"id\": 1,\"title\": \"111\",\"parentId\": null,\"parentName\": null},"+
"{\"id\": 2,\"title\": \"测试\",\"parentId\": 1,\"parentName\": \"111\"},"+
"{\"id\": 3,\"title\": \"123\",\"parentId\": 2,\"parentName\": \"测试\"}"+
"]";
List<TestVo> TestVos = ( List<TestVo>) new Gson().fromJson( str, new TypeToken<List<TestVo>>(){}.getType() );
List<TestVo> TestVoTree = TreeUtils.getTree( TestVos);
System.out.print( new Gson().toJson( TestVoTree ) );
}
}
打印出的数据:[{"childeNode":false,"id":1,"title":"111","children":[{"childeNode":false,"id":2,"title":"测试","parentId":1,"parentName":"111","children":[{"childeNode":false,"id":3,"title":"123","parentId":2,"parentName":"测试","children":[]}]}]}]
页面显示样式(iview显示样式)
大家如果有更好的方式,希望提出来哈