Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From snake_case to camelCase in Java

Tags:

java

string

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.

like image 328
Domenico Avatar asked Dec 11 '15 17:12

Domenico


2 Answers

Java SE 8+

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

Java SE 9+

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

like image 107
Arvind Kumar Avinash Avatar answered Sep 20 '22 04:09

Arvind Kumar Avinash


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
like image 22
Alex Avatar answered Sep 21 '22 04:09

Alex