private static Pattern linePattern = Pattern.compile("_(\\w)");
/**
* map转Bean
* @param map
* @param bean
* @param <T>
* @return
*/
public static <T> T mapToBean(Map<String, Object> map, T bean) {
Map<String, Object> resMap = new HashMap<>();
BeanMap beanMap = BeanMap.create(bean);
map.forEach((k,v) ->{
resMap.put(lineToHump(k),v);
});
beanMap.putAll(resMap);
return bean;
}
public static <T> List<T> mapsToBeans(List<Map<String, Object>> maps, Class<T> clazz){
return CollectionUtils.isEmpty(maps) ? Collections.emptyList() : maps.stream().map((v) -> {
try {
return mapToBean(v,clazz.getDeclaredConstructor().newInstance());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}).collect(Collectors.toList());
}
/**
* 下划线转驼峰命名
* @param str
* @return
*/
public static String lineToHump(String str) {
str = str.toLowerCase();
Matcher matcher = linePattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
return sb.toString();
}