摘要: 使用Java语言递归地将Map里的字段名由驼峰转下划线。通过此例可以学习如何递归地解析任意嵌套的List-Map容器结构。

难度:初级

概述###

在进行多语言混合编程时,由于编程规范的不同, 有时会需要进行字段名的驼峰-下划线转换。比如 php 语言中,变量偏向于使用下划线,而Java 语言中,变量偏向于驼峰式。当 PHP 调用 java 接口时,就需要将 java 返回数据结构中的驼峰式的字段名称改为下划线。使用 jackson 解析 json 数据时,如果不指定解析的类,常常会将 json 数据转化为 LinkedHashMap 。 因此,需要将 LinkedHashMap 里的字段名由驼峰转为下划线。

这里的难点是, Map 结构可能是非常复杂的嵌套结构,一个 Map 的某个 key 对应的 value 可能是原子的,比如字符串,整数等,可能是嵌套的 Map, 也可能是含有多个 Map 的 List , 而 map , list 内部又可能嵌套任意的 map 或 list . 因此,要使用递归的算法来将 value 里的 key 递归地转化为下划线。

算法设计###

首先,要编写一个基本函数 camelToUnderline,将一个字符串的值从驼峰转下划线。这个函数不难,逐字符处理,遇到大写字母就转成 _ + 小写字母 ; 或者使用正则表达式替换亦可;

其次,需要使用基本函数 camelToUnderline 对可能多层嵌套的 Map 结构进行转化。

假设有一个函数 transferKeysFromCamelToUnderline(amap) , 可以将 amap 里的所有 key 从驼峰转化为下划线,包括 amap 里嵌套的任意 map。返回结果是 resultMap ;

(1) 首先考虑最简单的情况:没有任何嵌套的情况,原子类型的 key 对应原子类型的 value ; resultMap.put(newkey, value) 即可 , newkey = camelToUnderline(key);

(2) 其次考虑 Map 含有嵌套 subMap 的情况: 假设 <key, value> 中,value 是一个 subMap, 那么,调用 camelToUnderline(key) 可以得到新的 newkey ,调用 transferKeysFromCamelToUnderline(subMap) 就得到转换了的 newValue , 得到 <newkey, newValue>; resultMap.put(newkey, newValue)

(3) 其次考虑 Map 含有 List 的情况: List 里通常含有多个 subMap , 只要遍历里面的 subMap 进行转换并添加到新的 List, 里面含有所有转换了的 newValue = map(transferKeysFromCamelToUnderline, List[subMap]); resultMap.put(newkey, newValue) .

递归技巧####

当使用递归方式思考的时候,有三个技巧值得注意:

(1) 首先,一定从最简单的情况开始思考。 这是基础,也是递归终结条件;

(2) 其次,要善于从语义上去理解,而不是从细节上。 比如说 Map 含有嵌套 subMap 的时候, 就不要细想 subMap 里面是怎样复杂的结构,是单纯的一个子 map ,还是含有 List 的 Map 的 Map 的 Map; 这样想会Feng掉滴_ 只需要知道 transferKeysFromCamelToUnderline(amap) 能够对任意复杂结构的 amap 进行转换得到所有 key 转换了的 resultMap , 而在主流程中直接使用这个 subResultMap 即可。这个技巧值得多体会多训练下才能掌握。

(3) 结果的存放。 既可以放在参数里,在递归调用的过程中逐步添加完善,也可以放在返回结果中。代码实现中展示了两种的用法。从某种意义来说,递归特别需要仔细地设计接口 transferKeysFromCamelToUnderline ,并从接口的语义上去理解和递归使用。

代码实现###

/**
* Created by shuqin on 16/11/3.
* Improved by shuqin on 17/12/31.
*/
package zzz.study.datastructure.map; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Function; public class TransferUtil { public static final char UNDERLINE='_'; public static String camelToUnderline(String origin){
return stringProcess(
origin, (prev, c) -> {
if (Character.isLowerCase(prev) && Character.isUpperCase(c)) {
return "" + UNDERLINE + Character.toLowerCase(c);
}
return ""+c;
}
);
} public static String underlineToCamel(String origin) {
return stringProcess(
origin, (prev, c) -> {
if (prev == '_' && Character.isLowerCase(c)) {
return "" + Character.toUpperCase(c);
}
if (c == '_') {
return "";
}
return ""+c;
}
);
} public static String stringProcess(String origin, BiFunction<Character, Character, String> convertFunc) {
if (origin==null||"".equals(origin.trim())){
return "";
}
String newOrigin = "0" + origin;
StringBuilder sb=new StringBuilder();
for (int i = 0; i < newOrigin.length()-1; i++) {
char prev = newOrigin.charAt(i);
char c=newOrigin.charAt(i+1);
sb.append(convertFunc.apply(prev,c));
}
return sb.toString();
} public static void tranferKeyToUnderline(Map<String,Object> map,
Map<String,Object> resultMap,
Set<String> ignoreKeys) {
Set<Map.Entry<String,Object>> entries = map.entrySet();
for (Map.Entry<String, Object> entry: entries) {
String key = entry.getKey();
Object value = entry.getValue();
if (ignoreKeys.contains(key)) {
resultMap.put(key, value);
continue;
}
String newkey = camelToUnderline(key);
if ( (value instanceof List) ) {
List newList = buildValueList(
(List) value, ignoreKeys,
(m, keys) -> {
Map subResultMap = new HashMap();
tranferKeyToUnderline((Map) m, subResultMap, ignoreKeys);
return subResultMap;
});
resultMap.put(newkey, newList);
}
else if (value instanceof Map) {
Map<String, Object> subResultMap = new HashMap<String,Object>();
tranferKeyToUnderline((Map)value, subResultMap, ignoreKeys);
resultMap.put(newkey, subResultMap);
}
else {
resultMap.put(newkey, value);
}
}
} public static Map<String,Object> tranferKeyToUnderline2(Map<String,Object> map,
Set<String> ignoreKeys) {
Set<Map.Entry<String,Object>> entries = map.entrySet();
Map<String,Object> resultMap = new HashMap<String,Object>();
for (Map.Entry<String, Object> entry: entries) {
String key = entry.getKey();
Object value = entry.getValue();
if (ignoreKeys.contains(key)) {
resultMap.put(key, value);
continue;
}
String newkey = camelToUnderline(key);
if ( (value instanceof List) ) {
List valList = buildValueList((List)value, ignoreKeys,
(m, keys) -> tranferKeyToUnderline2(m, keys));
resultMap.put(newkey, valList);
}
else if (value instanceof Map) {
Map<String, Object> subResultMap = tranferKeyToUnderline2((Map)value, ignoreKeys);
resultMap.put(newkey, subResultMap);
}
else {
resultMap.put(newkey, value);
}
}
return resultMap;
} public static List buildValueList(List valList, Set<String> ignoreKeys,
BiFunction<Map, Set, Map> transferFunc) {
if (valList == null || valList.size() == 0) {
return valList;
}
Object first = valList.get(0);
if (!(first instanceof List) && !(first instanceof Map)) {
return valList;
}
List newList = new ArrayList();
for (Object val: valList) {
Map<String,Object> subResultMap = transferFunc.apply((Map) val, ignoreKeys);
newList.add(subResultMap);
}
return newList;
} public static Map<String,Object> generalMapProcess(Map<String,Object> map,
Function<String, String> keyFunc,
Set<String> ignoreKeys) {
Map<String,Object> resultMap = new HashMap<String,Object>();
map.forEach(
(key, value) -> {
if (ignoreKeys.contains(key)) {
resultMap.put(key, value);
}
else {
String newkey = keyFunc.apply(key);
if ( (value instanceof List) ) {
resultMap.put(keyFunc.apply(key),
buildValueList((List) value, ignoreKeys,
(m, keys) -> generalMapProcess(m, keyFunc, ignoreKeys)));
}
else if (value instanceof Map) {
Map<String, Object> subResultMap = generalMapProcess((Map) value, keyFunc, ignoreKeys);
resultMap.put(newkey, subResultMap);
}
else {
resultMap.put(keyFunc.apply(key), value);
}
}
}
);
return resultMap;
} }

补位技巧####

无论是下划线转驼峰,还是驼峰转下划线,需要将两个字符作为一个组块进行处理,根据两个字符的情况来判断和转化成特定字符。比如下划线转驼峰,就是 _x => 到 X, 驼峰转下划线,就是 xY => x_y。 采用了前面补零的技巧,是的第一个字符与其他字符都可以用相同的算法来处理(如果不补零的话,第一个字符就必须单独处理)。

字符转换函数####

为了达到通用性,这里也使用了函数接口 BiFunction<Character, Character, String> convertFunc ,将指定的两个字符转换成指定的字符串。流程仍然是相同的:采用逐字符处理。

一个小BUG####

细心的读者会发现一个小BUG,就是当List里的元素不是Map时,比如 "buyList": ["Food","Dress","Daily"], 程序会抛异常:Cannot cast to java.util.Map。 怎么修复呢? 需要抽离出个函数,专门对 List[E] 的值做处理,这里 E 不是 Map 也不是List。这里不考虑 List 直接嵌套 List 的情况。

public static List buildValueList(List valList, Set<String> ignoreKeys,
BiFunction<Map, Set, Map> transferFunc) {
if (valList == null || valList.size() == 0) {
return valList;
}
Object first = valList.get(0);
if (!(first instanceof List) && !(first instanceof Map)) {
return valList;
}
List newList = new ArrayList();
for (Object val: valList) {
Map<String,Object> subResultMap = transferFunc.apply((Map) val, ignoreKeys);
newList.add(subResultMap);
}
return newList;
}

由于 buildValueList 需要回调tranferKeyToUnderlineX 来生成转换后的Map,这里使用了BiFunction<Map, Set, Map> transferFunc。相应的, tranferKeyToUnderline 和 tranferKeyToUnderline2 的列表处理要改成:

tranferKeyToUnderline:
if ( (value instanceof List) ) {
List newList = buildValueList(
(List) value, ignoreKeys,
(m, keys) -> {
Map subResultMap = new HashMap();
tranferKeyToUnderline((Map) m, subResultMap, ignoreKeys);
return subResultMap;
});
resultMap.put(newkey, newList);
} tranferKeyToUnderline2:
if ( (value instanceof List) ) {
List valList = buildValueList((List)value, ignoreKeys,
(m, keys) -> tranferKeyToUnderline2(m, keys));
resultMap.put(newkey, valList);
}

通用化####

对于复杂Map结构的处理,写一遍不容易,如果要做类似处理,是否可以复用上述处理流程呢? 上述主要的不同在于 key 的处理。只要传入 key 的处理函数keyFunc即可。这样,当需要从下划线转驼峰时,就不需要复制代码,然后只改动一行了。代码如下所示,使用了 Java8Map 遍历方式使得代码更加简洁可读。

public static Map<String,Object> generalMapProcess(Map<String,Object> map,
Function<String, String> keyFunc,
Set<String> ignoreKeys) {
Map<String,Object> resultMap = new HashMap<String,Object>();
map.forEach(
(key, value) -> {
if (ignoreKeys.contains(key)) {
resultMap.put(key, value);
}
else {
String newkey = keyFunc.apply(key);
if ( (value instanceof List) ) {
resultMap.put(keyFunc.apply(key),
buildValueList((List) value, ignoreKeys,
(m, keys) -> generalMapProcess(m, keyFunc, ignoreKeys)));
}
else if (value instanceof Map) {
Map<String, Object> subResultMap = generalMapProcess((Map) value, keyFunc, ignoreKeys);
resultMap.put(newkey, subResultMap);
}
else {
resultMap.put(keyFunc.apply(key), value);
}
}
}
);
return resultMap;
}

单测####

使用Groovy来对上述代码进行单测。因为Groovy可以提供非常方便的Map构造。单测代码如下所示:

TransferUtils.groovy

package cc.lovesq.study.test

import zzz.study.datastructure.map.TransferUtil

import static zzz.study.datastructure.map.TransferUtil.*

/**
* Created by shuqin on 17/12/31.
*/
class TransferUtilTest { static void main(String[] args) { [null, "", " "].each {
assert "" == camelToUnderline(it)
}
["isBuyGoods": "is_buy_goods", "feeling": "feeling", "G":"G", "GG": "GG"].each {
key, value -> assert camelToUnderline(key) == value
} [null, "", " "].each {
assert "" == underlineToCamel(it)
}
["is_buy_goods": "isBuyGoods", "feeling": "feeling", "b":"b", "_b":"B"].each {
key, value -> assert underlineToCamel(key) == value
} def amap = ["code": 200,
"msg": "successful",
"data": [
"total": 2,
"list": [
["isBuyGoods": "a little", "feeling": ["isHappy": "ok"]],
["isBuyGoods": "ee", "feeling": ["isHappy": "haha"]],
],
"extraInfo": [
"totalFee": 1500, "totalTime": "3d",
"nestInfo": [
"travelDestination": "xiada",
"isIgnored": true
],
"buyList": ["Food","Dress","Daily"]
]
],
"extendInfo": [
"involveNumber": "40",
]
]
def resultMap = [:]
def ignoreSets = new HashSet()
ignoreSets.add("isIgnored")
tranferKeyToUnderline(amap, resultMap, ignoreSets)
println(resultMap) def resultMap2 = tranferKeyToUnderline2(amap, ignoreSets)
println(resultMap2) def resultMap3 = generalMapProcess(amap, TransferUtil.&camelToUnderline, ignoreSets)
println(resultMap3) def resultMap4 = generalMapProcess(resultMap3, TransferUtil.&underlineToCamel, ignoreSets)
println(resultMap4) }
}

小结###

本文使用Java语言递归地将复杂的嵌套Map里的字段名由驼峰转下划线,并给出了更通用的代码形式,同时展示了如何处理复杂的嵌套结构。复杂的结构总是由简单的子结构通过组合和嵌套而构成,通过对子结构分而治之,然后使用递归技术来组合结果,从而实现对复杂结构的处理。

通过此例,学习了:

  • 设计递归程序来解析任意嵌套的List-Map容器结构;
  • 使用函数接口使代码更加通用化;
  • 使用Groovy来进行单测。

递归将Map里的字段名由驼峰转为下划线的更多相关文章

  1. Java实现递归将嵌套Map里的字段名由驼峰转为下划线

    摘要: 使用Java语言递归地将Map里的字段名由驼峰转下划线.通过此例可以学习如何递归地解析任意嵌套的List-Map容器结构. 难度:初级 概述 在进行多语言混合编程时,由于编程规范的不同, 有时 ...

  2. Mybatis处理列名—字段名映射— 驼峰式命名映射

    规范命名,数据库字段名使用 : 下划线命名(user_id) 类属性使用 : 驼峰命名(userId) 配置mybatis 时,全局设置: <settings> <!-- 开启驼峰, ...

  3. php 变量名前加一个下划线含义

    https://segmentfault.com/q/1010000006467833 一个下划线是私有变量以及私有方法两个下划线是PHP内置变量. 以下划线开头,表示为类的私有成员. 这只是个不成文 ...

  4. vue里面的v-model的变量不要使用下划线

    遇到一个问题,就是如果变量名是text_right,的时候更改v-model的值,则text_right不会更新,如果改成textRight就会更新,目前还不知道原因,先记录下来

  5. Sybase datetime 时间转换格式 convert(varchar(10),字段名,转换格式)

    convert(varchar(10),字段名,转换格式)sybase下convert函数第三个参数(时间格式)比如:1.select user_id,convert(varchar(10),dayt ...

  6. Python中变量名里面的下划线

    1 变量名前后都有两个下划线(__X__),表示是系统级变量: 2 变量名前只有一个下划线(_X),表示该变量不是由from module import *导入进来的: 3 变量名前有两个下划线(__ ...

  7. [原创]java WEB学习笔记59:Struts2学习之路---OGNL,值栈,读取对象栈中的对象的属性,读取 Context Map 里的对象的属性,调用字段和方法,数组,list,map

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  8. sql server递归子节点、父节点,sql查询表结构,根据字段名查所在表

    一.查询当前部门下的所有子部门 WITH dept AS ( SELECT * FROM dbo.deptTab --部门表 WHERE pid = @id UNION ALL SELECT d.* ...

  9. 一个list<Map>里map其中的一个字段的值相同,如何判断这个字段相同,就把这个map的其他字段存入另一个map中

    //不建议使用Map保存这些,使用实体bean更好 package com.rxlamo.zhidao;   import java.util.*;   public class Main {     ...

随机推荐

  1. 如何Recycle一个SharePoint Web Application,以及为什么

    当你发现SharePoint服务器的CPU或者内存使用率居高不下的时候,很多人都会选择iisreset来让资源使用率降下来.但是在企业环境中,这毫无疑问会使这台服务器中断服务从而影响到用户的使用,所以 ...

  2. android删除无用资源文件的python脚本

    随着android项目的进行,如果没有及时删除无用的资源时安装包会越来越大,是时候整理一下废弃资源缩小压缩包了,少年! 其实判断一个资源(drawable,layout)是否没有被使用很简单,文件名( ...

  3. 关于Hibernate 5 和 Hibernate 4 在创建SessionFactory的不同点分析(解决 org.hibernate.MappingException: Unknown entity: xx类报错问题)

    Hibernate4版本的SessionFactory实例构建的步骤是这样的(也是很多学习资料的通用范本): //Configuration就是代表着hibernate的那个xml配置文件对象,如果c ...

  4. 如何在CentOS配置Apache的HTTPS服务

    http://www.4byte.cn/learning/120027/ru-he-zai-centos-pei-zhi-apache-de-https-fu-wu.html

  5. [bzoj1087][scoi2005]互不侵犯king

    题目大意 在N×N的棋盘里面放K个国王,使他们互不攻击,共有多少种摆放方案.国王能攻击到它上下左右,以及左上 左下右上右下八个方向上附近的各一个格子,共8个格子. 思路 首先,搜索可以放弃,因为这是一 ...

  6. Intellij IDEA如何使用Maven Tomcat Plugin运行web项目(转)

    首先,Run --> Edit Configurations,这时候如下图: 然后点击左上角的加号,可以添加一个新的配置,如下图: 选择Maven,如下图: 下面填上自己的配置信息,点击appl ...

  7. lnmp配置Yii2规则

    nginx配置: 参考地址:http://www.cnblogs.com/grimm/p/5389970.html location / { try_files $uri $uri/ /index.p ...

  8. 用css实现网站切角效果 使用css3属性:渐变

     都是大量的练习,老师练习乒乓球花了大量时间,十万次一个动作的重复,高中班主任说过,世上没有天才,只是重复的次数多了,自然被认作了天才,小小班的学生之所以厉害是因为他们重复一个知识点次数多,所以没有一 ...

  9. 研究Mysql优化得出一些建设性的方案

    博客出自:http://blog.csdn.net/liuxian13183,转载注明出处! All Rights Reserved ! 熟悉网络请求路径,网址经过浏览器的URL验证,是否正确证书是否 ...

  10. git-credential-winstore.exe": No such file or directory

    $ git push -u origin master\"D:/GitExtensions/GitCredentialWinStore/git-credential-winstore.exe ...