?树结构:
@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;
}
}
}
参考