文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java实现级联下拉结构的示例代码

2024-04-02 19:55

关注

前言

在开发过程中,会遇到很多的实体需要将查出的数据处理为下拉或者级联下拉的结构,提供给前端进行展示。

在数据库查出的结构中,可能是集合<实体类>的结构,也有可能是List<Map>的结构。

在下拉或者级联下拉的节点数据中,有时候还需要动态的携带其他的参数,已便于前端对某些数据的显示

如区域的级联下拉树中,需要携带经纬度的区域–在选择的时候在地图展示该区域

基于上面的业务场景,构建了下面的工具类,不当的地方请大家多多指教

注:在构建下拉树的时候,会存在父类id的判断,可能没有涵盖到你们的使用情况,自行修改添加

构建统一返回下拉结构


@ApiModel("下拉树结构")
public class TreeSelect implements Serializable {
    private static final long serialVersionUID = 1L;

    
    @ApiModelProperty("节点id")
    private String id;

    
    @ApiModelProperty("节点名")
    private String label;

    
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @ApiModelProperty("节点携带数据")
    private Map<String, Object> dataMap;


    
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @ApiModelProperty("子节点集合")
    private List<TreeSelect> children;


    public TreeSelect() {

    }


    public String getId() {
        return id;
    }

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

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

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

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

    public Map<String, Object> getDataMap() {
        return dataMap;
    }

    public void setDataMap(Map<String, Object> dataMap) {
        this.dataMap = dataMap;
    }

构建集合<对象>转下拉树工具类


public class TreeSelectUtils {
    private static final Logger log = LoggerFactory.getLogger(TreeSelectUtils.class);
    
    public static final String ID = "id";
    
    public static final String PARENT = "parentId";

    
    public static final String LABEL = "name";


    
    public static <E> List<TreeSelect> singleTree(Collection<E> collection, String id, String label,
                                                  Class<?> clazz, String... args) {
        try {
            if (collection == null || collection.isEmpty()) {
                return null;
            }
            Field idField;
            try {
                idField = clazz.getDeclaredField(id);
            } catch (NoSuchFieldException e1) {
                idField = clazz.getSuperclass().getDeclaredField(id);
            }
            Field labelField;
            try {
                labelField = clazz.getDeclaredField(label);
            } catch (NoSuchFieldException e1) {
                labelField = clazz.getSuperclass().getDeclaredField(label);
            }
            idField.setAccessible(true);
            labelField.setAccessible(true);
            List<TreeSelect> list = new ArrayList<>();
            for (E e : collection) {
                TreeSelect select = new TreeSelect();
                select.setId(String.valueOf(idField.get(e)));
                select.setLabel(String.valueOf(labelField.get(e)));
                list.add(select);
                dynamicData(select, e, clazz, args);
            }
            idField.setAccessible(false);
            labelField.setAccessible(false);
            return list;
        } catch (Exception e) {
            log.error("单层下拉异常:", e);
            e.printStackTrace();
            return null;
        }
    }

    
    public static <E> List<TreeSelect> toTree(@NotNull Collection<E> collection, @NotNull Class<?> clazz,
                                              String... args) {
        return toTree(collection, null, null, null, clazz, args);
    }

    
    public static <E> List<TreeSelect> toTree(@NotNull Collection<E> collection, @NotEmpty String label,
                                              @NotNull Class<?> clazz, String... args) {
        return toTree(collection, null, null, label, clazz, args);
    }

    
    public static <E> List<TreeSelect> toTree(@NotNull Collection<E> collection, @NotEmpty String id, @NotEmpty String label,
                                              @NotNull Class<?> clazz, String... args) {
        return toTree(collection, id, null, label, clazz, args);
    }

    
    public static <E> List<TreeSelect> toTree(@NotNull Collection<E> collection, String id, String parent, String label,
                                              @NotNull Class<?> clazz, String... args) {
        try {
            if (collection == null || collection.isEmpty()) {
                return null;
            }
            //可以默认名称
            if (StringUtils.isEmpty(id)) {
                id = ID;
            }
            if (StringUtils.isEmpty(parent)) {
                parent = PARENT;
            }
            if (StringUtils.isEmpty(label)) {
                label = LABEL;
            }
            //是对象
            return collectionObj(collection, id, parent, label, clazz, args);
        } catch (Exception e) {
            log.error("多层下拉树异常:", e);
            return null;
        }
    }


    
    private static <E> List<TreeSelect> collectionObj(@NotNull Collection<E> collection, String id, String parent, String label,
                                                     @NotNull Class<?> clazz, String... args) throws NoSuchFieldException, IllegalAccessException {
        // 初始化根节点集合
        List<TreeSelect> list = new ArrayList<>();
        // 获取 id 字段, 从当前对象或其父类
        Field idField;
        try {
            idField = clazz.getDeclaredField(id);
        } catch (NoSuchFieldException e1) {
            idField = clazz.getSuperclass().getDeclaredField(id);
        }
        // 获取 parentId 字段, 从当前对象或其父类
        Field parentField;
        try {
            parentField = clazz.getDeclaredField(parent);
        } catch (NoSuchFieldException e1) {
            parentField = clazz.getSuperclass().getDeclaredField(parent);
        }
        // 获取 label 字段, 从当前对象或其父类
        Field labelField;
        try {
            labelField = clazz.getDeclaredField(label);
        } catch (NoSuchFieldException e1) {
            labelField = clazz.getSuperclass().getDeclaredField(label);
        }
        idField.setAccessible(true);
        parentField.setAccessible(true);
        labelField.setAccessible(true);
        // 找出所有的根节点
        for (E e : collection) {
            Object parentId = parentField.get(e);
            if (isParentNode(parentId, idField, collection)) {
                TreeSelect select = new TreeSelect();
                select.setId(String.valueOf(idField.get(e)));
                select.setLabel(String.valueOf(labelField.get(e)));
                list.add(select);
                dynamicData(select, e, clazz, args);
            }
        }
        // 依次添加子节点
        for (TreeSelect select : list) {
            addChild(select, collection, idField, parentField, labelField, clazz, args);
        }
        idField.setAccessible(false);
        parentField.setAccessible(false);
        labelField.setAccessible(false);
        return list;
    }


    
    private static <E> void dynamicData(@NotNull TreeSelect treeSelect, @NotNull Object e, @NotNull Class<E> clazz, String... args) throws IllegalAccessException, NoSuchFieldException {
        if (args.length > 0) {
            Map<String, Object> dataMap = new HashMap<>();
            for (String arg : args) {
                Field field;
                try {
                    field = clazz.getDeclaredField(arg);
                } catch (NoSuchFieldException e1) {
                    field = clazz.getSuperclass().getDeclaredField(arg);
                }
                field.setAccessible(true);
                dataMap.put(arg, field.get(e));
                field.setAccessible(false);
            }
            treeSelect.setDataMap(dataMap);
        }
    }


    
    private static <E> void addChild(@NotNull TreeSelect node, @NotNull Collection<E> collection,
                                     @NotNull Field idField, @NotNull Field parentField, @NotNull Field labelField,
                                     @NotNull Class<?> clazz, String... args) throws IllegalAccessException, NoSuchFieldException {
        //父节点的id
        String id = node.getId();
        //子节点集合
        List<TreeSelect> children = new ArrayList<>();
        for (E e : collection) {
            String parentId = String.valueOf(parentField.get(e));
            if (id.equals(parentId)) {
                // 将当前节点添加到目标节点的孩子节点
                TreeSelect treeSelect = new TreeSelect();
                treeSelect.setId(String.valueOf(idField.get(e)));
                treeSelect.setLabel(String.valueOf(labelField.get(e)));
                dynamicData(treeSelect, e, clazz, args);
                children.add(treeSelect);
                // 递归添加子节点
                addChild(treeSelect, collection, idField, parentField, labelField, clazz, args);
            }
        }
        node.setChildren(children);
    }

    
    private static <E> boolean isParentNode(Object parentId, Field idField, @NotNull Collection<E> collection) throws IllegalAccessException {
        if (parentId == null) {
            return true;
        } else if (parentId instanceof String && (StringUtils.isEmpty(String.valueOf(parentId)) || parentId.equals("0"))) {
            return true;
        } else if (parentId instanceof Long && Long.valueOf(0).equals(parentId)) {
            return true;
        } else {
            for (E e : collection) {
                Object o = idField.get(e);
                if (Objects.equals(o, parentId)) {
                    return false;
                }
            }
            return true;
        }
    }
}

构建List<Map>转下拉或下拉树的工具类


public class MapToTreeSelectUtils {
    private static final Logger log = LoggerFactory.getLogger(MapToTreeSelectUtils.class);
    
    public static final String DB_PARENT = "parent_id";

    
    public static List<TreeSelect> mapToTree(String id, String parent, String label,
                                             @NotNull List<Map<String, Object>> collection, String... args) {
        try {
            if (collection == null || collection.isEmpty()) {
                return new ArrayList<>();
            }
            //可以默认名称
            if (StringUtils.isEmpty(id)) {
                id = TreeSelectUtils.ID;
            }
            if (StringUtils.isEmpty(parent)) {
                parent = DB_PARENT;
            }
            if (StringUtils.isEmpty(label)) {
                label = TreeSelectUtils.LABEL;
            }
            return collectionMap(id, parent, label, collection, args);
        } catch (Exception e) {
            log.error("多层下拉树异常:", e);
            return null;
        }
    }

    
    private static List<TreeSelect> collectionMap(String id, String parent, String label,
                                                  @NotNull List<Map<String, Object>> collection, String... args) throws IllegalAccessException, NoSuchFieldException {
        List<TreeSelect> list = new ArrayList<>();
        // 找出所有的根节点
        for (Map<String, Object> next : collection) {
            Object parentId = next.get(parent);
            if (isParentNodeMap(parentId, id, collection)) {
                TreeSelect select = new TreeSelect();
                select.setId(String.valueOf(next.get(id)));
                select.setLabel(String.valueOf(next.get(label)));
                list.add(select);
                dynamicData(select, next, args);
            }
        }
        // 依次添加子节点
        for (TreeSelect select : list) {
            addChildMap(select, id, parent, label, collection, args);
        }
        return list;
    }


    
    private static void dynamicData(@NotNull TreeSelect treeSelect, @NotNull Map<String, Object> e, String... args) throws IllegalAccessException, NoSuchFieldException {
        if (args.length > 0) {
            Map<String, Object> dataMap = new HashMap<>();
            for (String arg : args) {
                dataMap.put(arg, e.get(arg));
            }
            treeSelect.setDataMap(dataMap);
        }
    }

    
    private static void addChildMap(@NotNull TreeSelect node, String id, String parent, String label,
                                    @NotNull List<Map<String, Object>> collection,
                                    String... args) throws IllegalAccessException, NoSuchFieldException {
        //父节点的id
        String nodeId = node.getId();
        //子节点集合
        List<TreeSelect> children = new ArrayList<>();
        for (Map<String, Object> e : collection) {
            String parentId = String.valueOf(e.get(parent));
            if (nodeId.equals(parentId)) {
                // 将当前节点添加到目标节点的孩子节点
                TreeSelect treeSelect = new TreeSelect();
                treeSelect.setId(String.valueOf(e.get(id)));
                treeSelect.setLabel(String.valueOf(e.get(label)));
                dynamicData(treeSelect, e, args);
                children.add(treeSelect);
                node.setChildren(children);
                // 递归添加子节点
                addChildMap(treeSelect, id, parent, label, collection, args);
            }
        }
    }


    
    private static boolean isParentNodeMap(Object parentId, String id, @NotNull List<Map<String, Object>> collection) {
        if (parentId == null) {
            return true;
        } else if (parentId instanceof String && (StringUtils.isEmpty(String.valueOf(parentId)) || parentId.equals("0"))) {
            return true;
        } else if (parentId instanceof Long && Long.valueOf(0).equals(parentId)) {
            return true;
        } else {
            for (Map<String, Object> e : collection) {
                Object o = e.get(id);
                if (Objects.equals(o, parentId)) {
                    return false;
                }
            }
            return true;
        }
    }
}

到此这篇关于Java实现级联下拉结构的示例代码的文章就介绍到这了,更多相关Java级联下拉内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯