多级属性名称转map

public static void main(String[] args) {
        List<String> fields = new ArrayList<>();
        fields.add("age");
        fields.add("name");
        fields.add("cardList.cardNumber");
        fields.add("cardList.createDate");
        fields.add("cardList.cardType.name");
        fields.add("cardList.cardType.pwdType");
        fields.add("cardList.cardType.enabled");
        Map<String, Object> stringObjectMap = BaseCurrentResource.fields2map(fields);
    }

    public static Map<String, Object> fields2map(List<String> fields) {
        Map<String, Object> map = new HashMap<>();
        for (String field : fields) {
            if (field.contains(".")) {
                String[] splits = field.split("\\.");
                field2tree(map, splits, 0, splits.length);
            } else {
                map.put(field, null);
            }
        }
        return map;
    }

    public static Map<String, Object> field2tree(Map<String, Object> map, String[] fields, int i, int n) {
        if (i >= n) {
            return map;
        }
        if (map == null) {
            map = new HashMap<>();
        }
        if (i == n - 1) {
            map.put(fields[i], null);
        } else {
            map.put(fields[i], field2tree((Map<String, Object>) map.get(fields[i]), fields, i + 1, n));
        }
        return map;
    }

 

posted @ 2022-05-12 18:39  1156740846  阅读(25)  评论(0编辑  收藏  举报