小驼峰转为下划线
可以通过正则表达式和字符串替换来将小驼峰转换为下划线格式,下面是代码示例
public class CamelToUnderscore {
/**
* 将小驼峰格式的字符串转换为下划线格式
*
* @param camel 小驼峰格式的字符串
* @return 下划线格式的字符串
*/
public static String camelToUnderscore(String camel) {
// 使用正则表达式将小驼峰格式的字符串替换为下划线格式
return camel.replaceAll("([A-Z])", "_$1").toLowerCase();
}
public static void main(String[] args) {
String str1 = "helloWorld";
String str2 = "myNameIsBond";
System.out.println(camelToUnderscore(str1)); // 输出:hello_world
System.out.println(camelToUnderscore(str2)); // 输出:my_name_is_bond
}
}
在上述代码中,camelToUnderscore
方法使用了正则表达式 ([A-Z])
将小驼峰格式的字符串中的大写字母匹配出来,并在其前面添加 _
,然后使用 toLowerCase()
方法将其转为小写字母。最终输出的字符串为下划线格式。
通过这种方式,我们可以将小驼峰格式的字符串转换成更符合数据库表字段命名规范的下划线格式。
下划线转为小驼峰
可以通过字符串分割和字符串拼接,将下划线格式的字符串转换为小驼峰格式。
public class UnderscoreToCamel {
/**
* 将下划线格式的字符串转换为小驼峰格式
*
* @param underscore 下划线格式的字符串
* @return 小驼峰格式的字符串
*/
public static String underscoreToCamel(String underscore) {
// 将下划线分割成单词数组
String[] words = underscore.split("_");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
String word = words[i].toLowerCase();
if (i != 0) {
// 第一个单词不需要大写
word = word.substring(0, 1).toUpperCase() + word.substring(1);
}
sb.append(word);
}
return sb.toString();
}
public static void main(String[] args) {
String str1 = "hello_world";
String str2 = "my_name_is_bond";
System.out.println(underscoreToCamel(str1)); // 输出:helloWorld
System.out.println(underscoreToCamel(str2)); // 输出:myNameIsBond
}
}
在上述代码中,underscoreToCamel
方法先使用 split
方法将下划线分割成单词数组,然后通过循环将单词转换为小驼峰格式,并使用 StringBuilder
进行拼接,最终输出小驼峰格式的字符串。
需要注意的是,第一个单词不需要大写,因为在小驼峰格式中,第一个单词的首字母依然是小写字母。
转小写+转驼峰
将map中的key转为小写并根据下划线转为小驼峰
- 将原始Map的所有的键转为小写形式
- 将小写键转换为小驼峰形式
Map<String, Integer> myMap = new HashMap<>(); myMap.put("FOO_BAR", 1); myMap.put("BAR_BAZ", 2); myMap.put("BAZ_QUX", 3); Map<String, Integer> result = myMap.entrySet().stream() .collect(Collectors.toMap(entry -> toCamelCase(entry.getKey()), Map.Entry::getValue)); System.out.println(result);
toCamelCase()
方法代码:private static String toCamelCase(String str) { String[] parts = str.toLowerCase().split("_"); StringBuilder builder = new StringBuilder(); for (int i = 0; i < parts.length; i++) { String part = parts[i]; builder.append(Character.toUpperCase(part.charAt(0))); if (part.length() > 1) { builder.append(part.substring(1)); } } return builder.toString(); } // {fooBar=1, barBaz=2, bazQux=3}
先将原始Map的所有键转为小写形式,然后再将小写键转为小驼峰形式。我们使用了自定义的
toCamelCase()
方法来实现将小写键转为小驼峰的需求。首先,我们将键按照下划线分割成多个部分,并且将每个部分的首字母大写化,然后再将所有的部分连接起来。