在实际的开发过程中时常需要将树型结构数据转换为普通集合或者将普通集合转换成树形结构数据,除了递归之外的转换方法
- TestDto.java
public class TestDto {
private int id;
private List<TestDto> childrens;
private int parentId;
public TestDto(int id, int parentId) {
this.id = id;
this.parentId = parentId;
}
}
- 普通数组转树形数组
public List<TestDto> toTree(List<TestDto> lists) {
for (TestDto dto : lists) {
final int id = dto.getId();
List<TestDto> childrens = dto.getChildrens();
if (childrens == null) {
childrens = new ArrayList<>();
}
for (TestDto test : lists) {
if (test.getParentId() == id) {
childrens.add(test);
}
}
dto.setChildrens(childrens);
}
for (int i = 0; i < lists.size(); i++) {
final TestDto testDt = lists.get(i);
if (testDt.getParentId() != 0) {
lists.remove(testDt);
i--;
}
}
return lists;
}
- 树形数组转普通数组
public List<TestDto> treeToList(List<TestDto> lists) {
List<TestDto> testDtoList = Lists.newArrayList();
for (int i = 0; i < lists.size(); i++) {
TestDto elementAt = lists.get(i);
testDtoList.add(elementAt);
final List<TestDto> childrens = elementAt.getChildrens();
if (CollectionUtils.isNotEmpty(childrens)) {
lists.addAll(childrens);
}
}
return testDtoList;
}
网友评论