Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.ArrayList;

import java.util.List;
import java.util.Map;

public class Main {
    public static List<Map<String, Object>> listToTree(List<Map<String, Object>> datas, String idField,
            String pIdField) {
        if (datas != null && datas.size() != 0) {
            ArrayList rootDatas = new ArrayList(datas.size());
            int length = datas.size();
            Map data = null;

            for (int i = 0; i < length; ++i) {
                data = (Map) datas.get(i);
                if (data.get(pIdField) == null || data.get(pIdField).toString().trim().length() == 0) {
                    rootDatas.add(data);
                    datas.remove(i);
                    --i;
                    --length;
                }
            }

            iterativeData(datas, rootDatas, idField, pIdField);
            return rootDatas;
        } else {
            return datas;
        }
    }

    private static void iterativeData(List<Map<String, Object>> datas, List<Map<String, Object>> parentDatas,
            String idField, String parentIdFiled) {
        int length = parentDatas.size();
        Map data = null;

        for (int i = 0; i < length; ++i) {
            data = (Map) parentDatas.get(i);
            ArrayList children = new ArrayList();
            data.put("children", children);
            int len = datas.size();
            Map d = null;

            for (int j = 0; j < len; ++j) {
                d = (Map) datas.get(j);
                if (data.get(idField).equals(d.get(parentIdFiled))) {
                    children.add(d);
                    datas.remove(j);
                    --j;
                    --len;
                }
            }

            iterativeData(datas, children, idField, parentIdFiled);
        }

    }
}