yucatio@システムエンジニア

趣味で作ったものいろいろ

【Java】スネークケース→キャメルケースに変換するプログラム

スネークケース(snake_case)からキャメルケース(camelCase)に変換するJavaのプログラムです。

  public static String toCamelCase(String text) {
    if (text == null) {
      return null;
    }
    if ("".equals(text)) {
      return "";
    }
    
    String[] words = text.split("_", 0);
    String camelWord = Arrays.stream(words)
        .filter(w -> !"".equals(w))
        .map(w -> Character.toUpperCase(w.charAt(0)) + w.substring(1))
        .collect(Collectors.joining(""));
    
    return Character.toLowerCase(camelWord.charAt(0)) + camelWord.substring(1);    
  }

簡単に解説すると、例えば"have_a_good_time"という入力の時、

  1. nullと空文字の場合は、それぞれnull, 空文字を返す
  2. "_"で文字を区切ります。(["have", "a", "good", "time"] の配列がえられます)
  3. 念のため空文字ははじきます
  4. 1文字目を大文字にしたものと2文字以降をつなげます(["Have", "A", "Good", "Time"])
  5. 配列の各要素をつなげます(HaveAGoodTime)
  6. 1文字目を小文字にしたものと、2文字目以降をつなげます(haveAGoodTime)

実行してみます

System.out.println(toCamelCase("a")); // a
System.out.println(toCamelCase("one_two_three")); // oneTwoThree