kotlin list集合树

kotlin list集合树


记录一下

data class AreaSchemaManageDto(
        var id: Long? = null,
        var pid: Long? = null,
        var label: String? = null,
        var children: MutableList<AreaSchemaManageDto>? = null
) : Serializable {
}

逻辑

  fun getAll(): List<AreaSchemaManageDto> {
        val list: List<AreaSchemaManageDto> = transaction {
            AreaSchemaManageDao.all().map { it.toModelDto() }
        }
        //最终树
        val treeList: MutableList<AreaSchemaManageDto> = mutableListOf()
        //获取根节点
        val rootList = list.stream().filter { dto -> dto.pid == 0L }.collect(Collectors.toList())
        //寻找子节点
        rootList.forEach { treeList.add(findChildren(it, list)) }

        return treeList
    }

    /**
     * 寻找子节点
     */
    private fun findChildren(tree: AreaSchemaManageDto, list: List<AreaSchemaManageDto>): AreaSchemaManageDto {
        list.stream().filter { node -> tree.id == node.pid }.collect(Collectors.toList()).forEach { node ->
            if (tree.children == null) {
                tree.children = mutableListOf()
            }
            tree.children!!.add(findChildren(node, list))
        }
        return tree
    }

你可能感兴趣的:(kotlin,list,开发语言)