参数排序:map结构的key排序-包含嵌套排序

1. 排序前的map:

{
  "data": {
    "testA": 20.45,
    "testC": "ok",
    "testB": 100,
    "dtL3": {
      "B": 1,
      "A": 10,
      "C": "1694833200000",
      "dtL4": {
        "11": 11,
        "21": "21",
        "33": 33
      }
    }
  }
}

2. 排序后的map

{
  "data": {
    "dtL3": {
      "A": 10,
      "B": 1,
      "C": "1694833200000",
      "dtL4": {
        "11": 11,
        "21": "21",
        "33": 33
      }
    },
    "testA": 20.45,
    "testB": 100,
    "testC": "ok"
  }
}

3. 排序方法记录

/**
 * map的key排序-嵌套递归(如果value也是map则需要递归进去排序)
 *
 * @param map
 * @return
 */
public static Map<String, Object> sortMap(Map<String, Object> map) {
    if (map == null || map.isEmpty()) {
        return map;
    }

    List<Map.Entry<String, Object>> entryList = new ArrayList<>(map.entrySet());
    Collections.sort(entryList, (o1, o2) -> {
        if (o1.getValue() instanceof Map && o2.getValue() instanceof Map) {
            return o1.getKey().compareTo(o2.getKey());
        } else {
            return o1.getKey().compareTo(o2.getKey());
        }
    });

    Map<String, Object> sortedMap = new LinkedHashMap<>();
    for (Map.Entry<String, Object> entry : entryList) {
        Object value = entry.getValue();
        if (value instanceof Map) {
            value = sortMap((Map<String, Object>) value);
        }
        sortedMap.put(entry.getKey(), value);
    }

    return sortedMap;
}

4. 初始化数据代码:

@Test
public void testSort() {
    Map<String, Object> dt = new LinkedHashMap<>();
    Map<String, Object> dtL2 = new LinkedHashMap();
    Map<String, Object> dtL3 = new LinkedHashMap();
    Map<String, Object> dtL4 = new LinkedHashMap();
    dtL4.put("11", 11);
    dtL4.put("33", 33);
    dtL4.put("21", "21");

    dtL3.put("B", 1);
    dtL3.put("A", 10);
    dtL3.put("C", "1694833200000");
    dtL3.put("dtL4", dtL4);

    dtL2.put("testA", 20.45);
    dtL2.put("testC", "ok");
    dtL2.put("testB", 100);
    dtL2.put("dtL3", dtL3);

    dt.put("data", dtL2);

    System.out.println(JSON.toJSONString(dt));
    System.out.println("<====[排序前;  排序后]=====>");

    Map<String, Object> stringObjectMap = sortMap(dt);
    System.out.println(JSON.toJSONString(stringObjectMap));
    System.out.println(JSON.toJSONString(dtL4));

}

丰木
322 声望19 粉丝

遇见超乎想象的自己!