按条件过滤树工具类,不保留子节点。
要保留子节点的话把注释的(// 去除子节点)这段去掉即可。
/**
* 按条件过滤树,不保留子节点
*
* @param tree 树型集合
* @param key 搜索的字段名称
* @param value 搜索的值
* @param childNodeName 子节点名称
* @param <T> 数据具体对象
* @return tree
*/
public static <T> List<T> filterTree(List<T> tree, String key, String value, String childNodeName) {
if (CollectionUtils.isEmpty(tree)) {
return new ArrayList<>();
}
JSONArray arr = JSONArray.parseArray(JSON.toJSONString(tree));
JSONArray result = filterTree(arr, key, value, childNodeName);
Type listType = new TypeReference<List<T>>() {}.getType();
return JSON.parseObject(result.toJSONString(), listType);
}
private static JSONArray filterTree(JSONArray tree, String key, String value, String childNodeName) {
Iterator<Object> it = tree.iterator();
while (it.hasNext()) {
JSONObject current = (JSONObject) it.next();
String currentValue = current.getString(key);
if(StringUtils.containsIgnoreCase(currentValue, value)) {
// 去除子节点 start
JSONArray childNodes = current.getJSONArray(childNodeName);
if(!CollectionUtils.isEmpty(childNodes)) {
JSONArray filterTree = filterTree(childNodes, key, value, childNodeName);
if(CollectionUtils.isEmpty(filterTree)) {
current.put(childNodeName, new JSONArray());
}
}
// 去除子节点 end
continue;
}
JSONArray childNodes = current.getJSONArray(childNodeName);
if(!CollectionUtils.isEmpty(childNodes)) {
filterTree(childNodes, key, value, childNodeName);
}
if(CollectionUtils.isEmpty(childNodes)) {
it.remove();
}
}
return tree;
}