public class TreeDemo { public static void main(String[] args) { //获取模拟数据 List<TreeModel> list = getListModel(); //转成SONString,方便格式化 String str = JSONObject.toJSONString(getTree(list,null)); System.out.println("result = "+str); } //***最重要的方法*** public static ...
publicstaticList<NodeVO>streamToTree(List<NodeVO>treeList,Integer parentId){returntreeList.stream()// 过滤父节点.filter(parent->Objects.equals(parent.getPid(),parentId))// 把父节点children递归赋值成为子节点.peek(child->child.setChildren(streamToTree(treeList,child.getId())).collect(Collectors....
三、list转树形方法 代码语言:javascript 代码运行次数:0 运行 AI代码解释 publicstaticList<NodeVO>streamToTree(List<NodeVO>treeList,String parentId){List<NodeVO>list=treeList.stream()// 过滤父节点.filter(parent->parent.getPid().equals(parentId))// 把父节点children递归赋值成为子节点.map(child->{...
代码示例如下: AI检测代码解析 publicstaticTreeNodebuildTree(List<TreeNode>nodes){Map<String,TreeNode>nodeMap=nodes.stream().collect(Collectors.toMap(node->node.id,Function.identity()));TreeNoderoot=null;for(TreeNodenode:nodes){if(node.parentId==null){root=node;}else{TreeNodeparent=nodeMap.get...
三、list转树形方法 public static List<NodeVO> streamToTree(List<NodeVO> treeList, String parentId) { List<NodeVO> list = treeList.stream() // 过滤父节点 .filter(parent -> parent.getPid().equals(parentId)) // 把父节点children递归赋值成为子节点 ...
.sorted(Comparator.comparingInt(GoodsCategory::getSort)) .map(entity->{ GoodsCategoryTree node=newGoodsCategoryTree(); BeanUtil.copyProperties(entity,node);//拷陪实体到组装的 tree中returnnode; }).collect(Collectors.toList());returnTreeUtil.build(treeList, CommonConstants.PARENT_ID); }...
可能平常会遇到一些需求,比如构建菜单,构建树形结构,数据库一般就使用父id来表示,为了降低数据库的查询压力,我们可以使用Java8中的Stream流一次性把数据查出来,然后通过流式处理,我们一起来看看,代码实现为了实现简单,就模拟查看数据库所有数据到List里面。 实体类:Menu.java /** * Menu * @author lcry */ @Data...
toCollection(()->newTreeSet<>(comparingLong(Apple::getId))), ArrayList::new) ); 回到顶部 8. 获取交集/并集/差集/去重并集 importstaticjava.util.stream.Collectors.toList;importjava.util.ArrayList;importjava.util.List;publicclassTest {publicstaticvoidmain(String[] args) { ...
使用TreeSet去重:TreeSet是一个有序的集合,不允许重复元素。我们可以使用TreeSet的add()方法将元素添加到集合中,如果元素已存在,则不会添加。示例代码:Set uniqueNumbers = new TreeSet<>(Arrays.asList(1, 2, 2, 3, 4, 4, 5)); 使用Collectors.toCollection()方法:我们可以使用Collectors类的toCollection(...
this.childList = childList; } } 第二步、递归组装树形结构 @Test publicvoidtesttree(){ //模拟从数据库查询出来 List<Menu> menus = Arrays.asList( newMenu(1,"根节点",0), newMenu(2,"子节点1",1), newMenu(3,"子节点1.1",2),