李锋镝的博客

  • 首页
  • 时间轴
  • 留言
  • 插件
  • 左邻右舍
  • 关于我
    • 关于我
    • 另一个网站
    • 我的导航站
  • 赞助
Destiny
自是人生长恨水长东
  1. 首页
  2. 原创
  3. 正文

多层嵌套map对象转扁平化map

2019年7月25日 22688点热度 0人点赞 0条评论

将深度嵌套的map对象转换为扁平化的map对象输出。

import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 李锋镝
 * @date Create at 14:12 2019/7/24
 */
public class MapFlatUtil {

    private static final String SEPARATOR = "_";

    /**
     * 深度嵌套map对象转大map(扁平化)
     * @param source 源map
     * @param parentNode 父节点扁平化之后的名字
     * @return map
     */
    public static Map<String, Object> flat(Map<String, Object> source, String parentNode) {
        Map<String, Object> flat = new HashMap<>();
        Set<Map.Entry<String, Object>> set  = source.entrySet();
        String prefix = StringUtils.isNotBlank(parentNode) ? parentNode + SEPARATOR : "";
        set.forEach(entity -> {
            Object value = entity.getValue();
            String key = entity.getKey();
            String newKey = prefix + key;
            if (value instanceof Map) {
                flat.putAll(flat((Map)value, newKey));
            } else {
                flat.put(newKey, value);
            }
        });
        return flat;
    }
    public static void main (String[] args) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        Map<String, Object> map3 = new HashMap<>();
        map.put("root", "root");
        map2.put("root", "root");
        map2.put("map3", map3);
        map3.put("root", "root");
        map.put("map2", map2);

        System.out.println(flat(map, null));
    }
}

输出:

{map2_map3_root=root, map2_root=root, root=root}

 

除非注明,否则均为李锋镝的博客原创文章,转载必须以链接形式标明本文链接

本文链接:https://www.lifengdi.com/article/534

相关文章

  • SpringBoot常用注解
  • CompletableFuture使用详解
  • 金融级JVM深度调优实战的经验和技巧
  • SpringBoot 中内置的 49 个常用工具类
  • SpringBoot 实现接口防刷的 5 种实现方案
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2019年7月25日

李锋镝

既然选择了远方,便只顾风雨兼程。

打赏 点赞
< 上一篇
下一篇 >

文章评论

1 2 3 4 5 6 7 8 9 11 12 13 14 15 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 57 58 60 61 62 63 64 65 66 67 69 72 74 76 77 78 79 80 81 82 85 86 87 90 92 93 94 95 96 97 98 99
取消回复

COPYRIGHT © 2025 lifengdi.com. ALL RIGHTS RESERVED.

Theme Kratos Made By Dylan

津ICP备2024022503号-3