公共方法
public static <T,V> List<T> buildTree(List<T> list, Function<T, V> idMapper, Function<T, V> pIdMapper,
Function<T, List<T>> getNodeMapper, BiConsumer<T, List<T>> setNodeMapper){
Map<V,T> vtMap = list.stream().collect(Collectors.toMap((idMapper),(value->value)));
list.clear();
for (Map.Entry<V, T> entry : vtMap.entrySet()) {
T t = entry.getValue();
V pId = pIdMapper.apply(t);
if(isValid(pId)){
T t1 = vtMap.get(pId);
if(t1 == null){//找不到该父id对应的数据
continue;
}
List<T> nodeList = getNodeMapper.apply(t1);
if(nodeList == null){
nodeList = new ArrayList();
setNodeMapper.accept(t1, nodeList);
}
nodeList.add(t);
} else {
list.add(t);
}
}
return list;
}
public static <V> boolean isValid(V value){
boolean flag = false;
if(null != value && value instanceof String && StringUtils.isNotNull(value)){
flag = true;
}
if(null != value && value instanceof Integer && 0 != ((Integer) value).intValue()){
flag = true;
}
return flag;
}
调用:
dtoList = commTree(dtoList, x->x.getId(), x->x.getParentId(), x->x.getNode(), KnowlCategoryDto::setNode);
注意:给属性赋值只能使用::而无法使用->