本文主要是介绍java之树筛选,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
树结构:
@Data
public class TreeNode {/*** 主键*/private String id;/*** 名称*/private String name;/*** 父节点id 最上层的父节点为0*/private String parentId;private List<TreeNode> children;
}
方法1:
public List<TreeNode> findTree(List<TreeNode> list, String keyword) {List<TreeNode> newNodes = new ArrayList<>();List<TreeNode> hitList = list.stream().filter(item -> item.getName().contains(keyword)).collect(Collectors.toList());Map<String, TreeNode> map = list.stream().collect(Collectors.toMap(TreeNode::getId, Function.identity()));for (TreeNode currentNode : hitList) {if (!newNodes.contains(currentNode)) {newNodes.add(currentNode);do {currentNode = map.get(currentNode.getParentId());if (null != currentNode) {if (newNodes.contains(currentNode)) {break;} else {newNodes.add(currentNode);}}} while (!"0".equals(currentNode.getParentId()));}}return newNodes;
}
方法2:
public static List<TreeNode> findTree(List<TreeNode> treeDtoList, String keyword) {//最后返回的筛选完成的集合List<TreeNode> screeningOfCompleteList = new ArrayList<>();if (CollectionUtils.isNotEmpty(treeDtoList) && StringUtils.isNotBlank(keyword)) {for (TreeNode treeDto : treeDtoList) {//递归筛选完成后的返回的需要添加的数据TreeNode addTreeDto = getSubsetPmsPlanPo(treeDto, keyword);if (null != addTreeDto) {screeningOfCompleteList.add(addTreeDto);}}return screeningOfCompleteList;}return null;
}/*** 筛选符合的集合并返回** @param treeDto 树形类* @param keyword 筛选条件* @return 筛选成功的类*/
public static TreeNode getSubsetPmsPlanPo(TreeNode treeDto,String keyword) {String nodeName = treeDto.getName(); //筛选条件if (CollectionUtils.isNotEmpty(treeDto.getChildren())) { //有子集时List<TreeNode> addTreeDtoList = new ArrayList<>(); // 符合筛选条件的子集for (TreeNode subsetTreeDto : treeDto.getChildren()) {// 继续向下寻找筛选符合的集合TreeNode newTreeDto = getSubsetPmsPlanPo(subsetTreeDto, keyword);if (null != newTreeDto) { //当子集筛选完不为空时添加addTreeDtoList.add(newTreeDto);}}if (CollectionUtils.isNotEmpty(addTreeDtoList)) {//符合筛选条件的子集不为空时// 替换子集集合内容并返回当前对象treeDto.setChildren(addTreeDtoList);return treeDto;} else if (CollectionUtils.isEmpty(addTreeDtoList) && nodeName.contains(keyword)) { ///符合筛选条件的子集为空且当前对象符合筛选条件// 返回当前对象return treeDto;} else { //子集及当前对象不符合筛选条件return null;}} else { //无子集时,判断当前对象是否符合筛选条件if (nodeName.contains(keyword)) {return treeDto;} else {return null;}}
}
参考
Java递归实现树结构遍历展示以及条件筛选_递归展示树形结构-CSDN博客
JAVA根据条件检索对树进行筛选_java中树结构展示中怎么根据条件进行筛选-CSDN博客
这篇关于java之树筛选的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!