Can anyone tell me how to convert a string in snake_case as:
camel_case
to a string in camelCase as:
camelCase
in Java?
Thank you in advance.
Using Java-8 Stream API, we can do it in a single statement.
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String str = "snake_case_to_camel_case";
str = str.indexOf("_") != -1
? str.substring(0, str.indexOf("_")) +
Arrays.stream(str.substring(str.indexOf("_") + 1).split("_"))
.map(s -> Character.toUpperCase(s.charAt(0)) + s.substring(1)).collect(Collectors.joining())
: str;
System.out.println(str);
}
}
Output:
snakeCaseToCamelCase
ONLINE DEMO
Matcher#replaceAll(Function<MatchResult, String> replacer)
introduced with Java SE 9, makes it further easy.
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "snake_case_to_camel_case";
str = Pattern.compile("_([a-z])")
.matcher(str)
.replaceAll(m -> m.group(1).toUpperCase());
System.out.println(str);
}
}
Output:
snakeCaseToCamelCase
ONLINE DEMO
Also Guava's CaseFormat offers quite a neat solution that allows you to transform from and to camel case and even other specific cases.
CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "camel_case"); // returns camelCase
CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "CAMEL_CASE"); // returns CamelCase
CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, "camelCase"); // returns CAMEL_CASE
CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, "CamelCase"); // returns camel-case
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With