Java树形结构查询(Steam)

  • Post author:
  • Post category:java


大部门场景需要展示树形结构的数据,目的是一目了然能够看明白数据,特别是对于组织或者一些企业以及部门

下面给大家讲一下我写树形结构时候的一个思路

1、了解树形结构是如何形成的:因为树形结构肯定是有父级和子级,这样才能够关联起来

2、在我的了解范围内,有两种,一种是无限层级,子级和父级在一张表里面,第二分别在两张表里面,需要关联查询

1.1那么我们第一步要做的就是先把最外层的节点构造出来,然后依次往子级里面放相关的数据

1、可以在实体里面 声明一个集合

2、拿到数据之后,先把最外层节点收集起来,下面给大家上代码,简单的实现

2.1.1实体类

public class TreeEntity implements Serializable {
        private Integer id; //子级
        private String name; //名称
        private Integer pid; //父级id
        @JsonInclude(JsonInclude.Include.NON_EMPTY) //忽略空值
        private List<TreeEntity> childrenList; //子级集合
}

2.2.2实现需求

public class TreeDemo{
       public static void main(String[] args) {
        List<TreeEntity> treeList = init();
        List<TreeEntity> collect = treeList.stream()
                .filter(item -> item.getPid() == 0)
                .map(item -> {
                    item.setChildrenList(getChildren(item, treeList));
                    return item;
                }).
                collect(Collectors.toList());
        System.out.println(new Gson().toJsonTree(collect));
    }

    private static List<TreeEntity> getChildren(TreeEntity treeEntity, List<TreeEntity> treeEntityList) {
        List<TreeEntity> collect = treeEntityList.stream()
                .filter(item -> item.getPid().equals(treeEntity.getId()))
                .map(item -> {
                    item.setChildrenList(getChildren(item, treeEntityList));
                    return item;
                })
                .collect(Collectors.toList());
        return collect;
    }

}

2.2.3结果集

[{
	"id": 1,
	"name": "1-1",
	"pid": 0,
	"childrenList": [{
		"id": 3,
		"name": "1-1-1",
		"pid": 1,
		"childrenList": [{
			"id": 7,
			"name": "1-1-1-1",
			"pid": 3,
			"childrenList": [{
				"id": 11,
				"name": "1-1-1-1-1",
				"pid": 7,
				"childrenList": []
			}]
		}, {
			"id": 8,
			"name": "1-1-1-2",
			"pid": 3,
			"childrenList": []
		}]
	}, {
		"id": 4,
		"name": "1-1-2",
		"pid": 1,
		"childrenList": []
	}]
}, {
	"id": 2,
	"name": "2-1",
	"pid": 0,
	"childrenList": [{
		"id": 5,
		"name": "2-1-1",
		"pid": 2,
		"childrenList": [{
			"id": 9,
			"name": "2-1-1-1",
			"pid": 5,
			"childrenList": [{
				"id": 12,
				"name": "2-1-1-1-1",
				"pid": 9,
				"childrenList": []
			}]
		}, {
			"id": 10,
			"name": "2-1-1-2",
			"pid": 5,
			"childrenList": []
		}]
	}, {
		"id": 6,
		"name": "2-1-2",
		"pid": 2,
		"childrenList": []
	}]
}]



版权声明:本文为xiaoxiaohan130原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。