Java converts a set of data into tree data

data
{"parentID": 0,"sequence": 0,"id": 1,"leaf": true,"children": []} 
{"parentID": 0,"sequence": 0,"id": 2,"leaf": true,"children": []}

requirements: efficiency

Apr.28,2022

two for loops. I can't think of any other good way for the time being.

public class Test {
    public static void main(String[] args) throws Exception {
        String json = "[{\"parentID\": 0,\"sequence\": 0,\"id\": 1,\"leaf\": true,\"children\": []},         {\"parentID\": 0,\"sequence\": 0,\"id\": 2,\"leaf\": true,\"children\": []},         {\"parentID\": 1,\"sequence\": 0,\"id\": 3,\"leaf\": true,\"children\": []},         {\"parentID\": 2,\"sequence\": 0,\"id\": 4,\"leaf\": true,\"children\": []},         {\"parentID\": 2,\"sequence\": 0,\"id\": 5,\"leaf\": true,\"children\": []}]";
        List<Root> rootList1 = JsonUtil.toList(json, Root.class);        
        Set<Integer> idSet = new HashSet<Integer>();    
        for(Root r : rootList1){
            idSet.add(r.getId());
        }
        for(Root r : rootList1){
            if(!idSet.contains(r.getParentID())){
                System.out.println(r);
            }
        }
    }
}

class Root{
    private Integer parentID;
    
    private Integer sequence;
    
    private Integer id;
    
    private boolean leaf;
    
    private List<Root> children;

    public Integer getParentID() {
        return parentID;
    }

    public void setParentID(Integer parentID) {
        this.parentID = parentID;
    }

    public Integer getSequence() {
        return sequence;
    }

    public void setSequence(Integer sequence) {
        this.sequence = sequence;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public boolean isLeaf() {
        return leaf;
    }

    public void setLeaf(boolean leaf) {
        this.leaf = leaf;
    }

    public List<Root> getChildren() {
        return children;
    }

    public void setChildren(List<Root> children) {
        this.children = children;
    }

    @Override
    public String toString() {
        return "Root [parentID=" + parentID + ", sequence=" + sequence
                + ", id=" + id + ", leaf=" + leaf + ", children=" + children
                + "]";
    }
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b4049c-2c4fa.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b4049c-2c4fa.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?