原文:Java8新特性-使用Stream流递归实现遍历树形结构
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class Test2Class {
@Data
public class Menu {
private Integer id;
private String name;
private Integer parentId;
private List<Menu> childList;
public Menu(Integer id, String name, Integer parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
}
@Test
public void test(){
List<Menu> menus = Arrays.asList(
new Menu(1,"根节点1",0),
new Menu(2,"子节点1.1",1),
new Menu(3,"子节点1.2",1),
new Menu(4,"子节点1.3",1),
new Menu(5,"子节点1.4",1),
new Menu(6,"根节点2",0),
new Menu(7,"子节点2.1",6),
new Menu(8,"子节点2.2",6),
new Menu(9,"子节点2.2.1",8),
new Menu(10,"子节点2.2.2",8),
new Menu(11,"根节点3",0),
new Menu(12,"子节点3.1",11)
);
//获取父节点
List<Menu> collect = menus.stream().filter(m-> m.getParentId()==0).map(
m->{
m.setChildList(getChildrens(m,menus));
return m;
}
).collect(Collectors.toList());
System.out.println(JSONObject.toJSON(collect));
}
public List<Menu> getChildrens(Menu root,List<Menu> all){
List<Menu> children = all.stream().filter(m-> Objects.equals(m.getParentId(),root.getId())).map(
m->{
m.setChildList(getChildrens(m,all));
return m;
}
).collect(Collectors.toList());
return children;
}
}
getChildrens也可以这么写,写在方法内:
BiFunction<Menu,List<Menu>,List<Menu>> getChildrens =new BiFunction<Menu, List<Menu>, List<Menu>>() {
@Override
public List<Menu> apply(Menu root, List<Menu> all) {
List<Menu> children = all.stream().filter(m-> Objects.equals(m.getParentId(),root.getId())).peek(
m-> m.setChildList(this.apply(m,all))
).collect(Collectors.toList());
return children;
}
};