What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

Solution 1:

Another option is using Google Guava's com.google.common.base.CaseFormat

George Hawkins left a comment with this example of usage:

CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "THIS_IS_AN_EXAMPLE_STRING");

Solution 2:

Take a look at WordUtils in the Apache Commons lang library:

Specifically, the capitalizeFully(String str, char[] delimiters) method should do the job:

String blah = "LORD_OF_THE_RINGS";
assertEquals("LordOfTheRings", WordUtils.capitalizeFully(blah, '_').replaceAll("_", ""));

Green bar!

Solution 3:

static String toCamelCase(String s){
   String[] parts = s.split("_");
   String camelCaseString = "";
   for (String part : parts){
      camelCaseString = camelCaseString + toProperCase(part);
   }
   return camelCaseString;
}

static String toProperCase(String s) {
    return s.substring(0, 1).toUpperCase() +
               s.substring(1).toLowerCase();
}

Note: You need to add argument validation.

Solution 4:

With Apache Commons Lang3 lib is it very easy.

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;

public String getName(String text) {
  return StringUtils.remove(WordUtils.capitalizeFully(text, '_'), "_");
}

Example:

getName("SOME_CONSTANT");

Gives:

"SomeConstant"