45

How can I convert snake case to camel case in Java?

Input: "input_in_snake_case"

Output: "InputInSnakeCase"

xskxzr
  • 12,442
  • 12
  • 37
  • 77
Kamesh
  • 1,435
  • 1
  • 14
  • 27

2 Answers2

114

Guava supports this through its CaseFormat class

import com.google.common.base.CaseFormat;


public class StackOverflow25680258 {

    public static void main(String[] args) {
        System.out.println(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "input_in_snake_case")); 
    }

}

Output

InputInSnakeCase
jneuendorf
  • 402
  • 6
  • 18
Adam
  • 35,919
  • 9
  • 100
  • 137
  • I have the same issue. But if word is helloFunnyWORLD, result should be hello-funny-world. Guava solution is not suitable for me. – Alexey Smirnov Jun 02 '17 at 20:15
  • 1
    Just out of curiosity why is the class name `StackOverflow25680258`? Do you have some sort of macro? – SureshS Mar 02 '18 at 10:30
  • 1
    @SureshS: the name of the method is given by the id of this question - see browser link :) – Paul May 26 '18 at 11:56
  • @Adam Is it possible to output: "inputInSnakeCase" ? I mean with first letter in lower case. (using guava not manually lower first letter) – Lucke Sep 04 '18 at 10:13
  • 3
    @Lucke Yes - use CaseFormat.LOWER_CAMEL instead of CaseFormat.UPPER_CAMEL – Adam Sep 04 '18 at 14:15
0

A java solution without dependencies assuming the input is actually snake case.

  public static String makeCamelCase(final String snakeCase) {
    var sb = new StringBuilder();
    var lastChar = snakeCase.charAt(0);
    sb.append(Character.toUpperCase(lastChar));
    for (int i =1; i < snakeCase.length(); i++) {
      var c = snakeCase.charAt(i);
      sb.append(c);
      if (lastChar == '_') {
        sb.delete(sb.length()-2, sb.length());
        sb.append("_" + Character.toUpperCase(c));
      }
      lastChar = c;
    }
    return sb.toString();
  }
John Gilmer
  • 864
  • 6
  • 10