java树结构实现方法

1.双层for循环

  List> result = newsflDao.fltree(userid);
        List> listvalue = new ArrayList<>();
        List> nodes;
        for (Map stringObjectMap : result) {
            nodes = new ArrayList<>();
            for (Map objectMap : result) {
                //给每个分类后面添加是否关注,默认为未关注
                if(!stringObjectMap.containsKey("is_gz")){
                    stringObjectMap.put("is_gz",0);
                }
                //把子类放进nodes中
                if (stringObjectMap.get("code").equals(objectMap.get("parent_code"))) {
                    nodes.add(objectMap);
                }
            }
            if (nodes.size() > 0) {
                stringObjectMap.put("nodes", nodes);
                listvalue.add(stringObjectMap);
            }
        }

2.递归

  public static List filterNode(TreeNode treeNode, List targetNode) {

        List nodes = treeNode.getChildren();
        List newNodes = Lists.newArrayList();
        List tagNodes = Lists.newArrayList();

        for (TreeNode node : nodes) {
            if (targetNode.contains(node.getNodeName())) {
                newNodes.add(node);
            }
            if (node.getChildren() != null && node.getChildren().size() > 0) {
                List retNodes = filterNode(node, targetNode);
                if (retNodes.size() > 0) {
                    node.setChildren(retNodes);
                } else {
                    // 没有子节点情况
                    node.setChildren(null);
                    // 标记,循环结束后删除
                    tagNodes.add(node);
                }
            }
        }
        nodes.removeAll(tagNodes);
        return newNodes;
    }

 

你可能感兴趣的:(java)