Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most elegant way to convert a hyphen separated word (e.g. "do-some-stuff") to the lower camel-case variation (e.g. "doSomeStuff")?

Tags:

java

What is the most elegant way to convert a hyphen separated word (e.g. "do-some-stuff") to the lower camel-case variation (e.g. "doSomeStuff") in Java?

like image 520
Christopher Klewes Avatar asked Sep 01 '10 13:09

Christopher Klewes


3 Answers

Use CaseFormat from Guava:

import static com.google.common.base.CaseFormat.*;

String result = LOWER_HYPHEN.to(LOWER_CAMEL, "do-some-stuff");
like image 85
Joachim Sauer Avatar answered Nov 11 '22 11:11

Joachim Sauer


With Java 8 there is finally a one-liner:

Arrays.stream(name.split("\\-"))
    .map(s -> Character.toUpperCase(s.charAt(0)) + s.substring(1).toLowerCase())
    .collect(Collectors.joining());

Though it takes splitting over 3 actual lines to be legible ツ

(Note: "\\-" is for kebab-case as per question, for snake_case simply change to "_")

like image 19
earcam Avatar answered Nov 11 '22 13:11

earcam


The following method should handle the task quite efficient in O(n). We just iterate over the characters of the xml method name, skip any '-' and capitalize chars if needed.

public static String toJavaMethodName(String xmlmethodName) { 
  StringBuilder nameBuilder = new StringBuilder(xmlmethodName.length());    
  boolean capitalizeNextChar = false;

  for (char c:xmlMethodName.toCharArray()) {
    if (c == '-') {
      capitalizeNextChar = true;
      continue;
    }
    if (capitalizeNextChar) {
      nameBuilder.append(Character.toUpperCase(c));
    } else {
      nameBuilder.append(c);
    }
    capitalizeNextChar = false;
  }
  return nameBuilder.toString();
}
like image 10
Andreas Dolk Avatar answered Nov 11 '22 12:11

Andreas Dolk