在开放过程中碰到许多需要组合成树的数据,会让我们比较头疼,下面公开一种比较实用的方法,希望能帮助到需要帮助的人。
话不多说上代码:
下面这个是转树的方法。
/**
* 列表转树(包含根节点)
* @param list
* @return
*/
@Override
public Tree getTreeFromList(List<Tree> list) {
Tree result = null;
if (list != null && list.size() > 0) {
for (Tree o : list) {
if (o.getId().equals(o.getParentId())) {
result = o;
}
for (Tree p : list) {
if (p.getId().equals(p.getParentId())) {
continue;
}
if (Objects.equals(p.getParentId(), o.getId())) {
List<Tree> children = o.getChildren();
if (children == null) {
children = new ArrayList<>();
o.setChildren(children);
}
o.getChildren().add(p);
}
}
}
}
return result;
}
/**
* 列表转树列表(不包含根节点)
* @param list
* @return
*/
@Override
public List<Tree> getTreeListFromList(List<Tree> list) {
List<Tree> result = Lists.newArrayList();
if (list != null && list.size() > 0) {
for (Tree o : list) {
if (o.getParentId().equals("1")) {
result.add(o);
}
for (Tree p : list) {
if (p.getId().equals(p.getParentId())) {
continue;
}
if (Objects.equals(p.getParentId(), o.getId())) {
List<Tree> children = o.getChildren();
if (children == null) {
children = new ArrayList<>();
o.setChildren(children);
}
o.getChildren().add(p);
}
}
}
}
return result;
}
这是所需要的通用实体。
@Getter
@Setter
public class Tree {
@ApiModelProperty("ID")
private String id;
@ApiModelProperty("节点名称")
private String label;
@ApiModelProperty("父节点id")
private String parentId;
@ApiModelProperty("子节点列表")
private List<Tree> children;
}
以上就是列表转树的代码。
有些坑不得不踩,有些事不得不做,希望能通过分享互相进步,走过这段平凡的路。