メンチカツには醤油でしょ!!

AWS/Java/Node.js/Spreadsheets/Docker/Jenkins/コミュニティ・勉強会レポを主とした技術系ブログ

Javaで英単語を単数形/複数形に変換する処理 (singularize/pluralize)

要件

英単語を単数形⇔複数形に変換したい、逆も然り、Javaで。

具体的には

単数形⇒複数形への変換は単語にsを付けるだけと思いきや
・box⇒boxes のようにesが付くパターン
・company⇒companies のようにyが消えてiesが付くパターン
・people⇒person のように違う単語になるパターン
・fish⇒fish のように複数形はそのままのパターン
など特例があったりして意外と面倒だったりもします。

ここまで見えてくると気合で実装だなんて時間の無駄はせずに
世の中に公開されているUtilクラスを使うのが良いと判断できますね。

Railsだとsingularize/pluralizeというのがあるのですが、
これをJavaでもやりたい。
この単語でググればいいのですが
そもそもこの一般的な処理名を知ってるかどうかが既にカギでしたね。

安心してください、ありまーす!

pom.xml

JBoss DNAというプロジェクトのInflectorクラスに実装がありますので
Mavenから取りましょう。
リモートリポジトリの追加設定と共に以下の通りです。

<dependencies>
  <!-- JBoss DNA -->
  <dependency>
    <groupId>org.jboss.dna</groupId>
    <artifactId>dna-common</artifactId>
    <version>0.7</version> <!-- 最新はhttps://repository.jboss.org/nexus/content/groups/public-jboss/org/jboss/dna/dna-common/ 参照 -->
  </dependency>
</dependencies>

<!-- 中略 -->

<repositories>
  <repository>
    <id>jboss-public-repository-group</id>
    <name>JBoss Public Maven Repository Group</name>
    <url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
    <layout>default</layout>
    <releases>
      <enabled>true</enabled>
      <updatePolicy>never</updatePolicy>
    </releases>
    <snapshots>
      <enabled>true</enabled>
      <updatePolicy>never</updatePolicy>
    </snapshots>
  </repository>
</repositories>

参考

developer.jboss.org

org.jboss.dna.common.text.Inflector

Inflector.getInstance().pluralize("box"); // You'll get "boxes".
Inflector.getInstance().pluralize("company"); // You'll get "companies".
Inflector.getInstance().pluralize("person"); // You'll get "people".
Inflector.getInstance().pluralize("fish"); // You'll get "fish".
Inflector.getInstance().singularize("boxes"); // You'll get "box".
Inflector.getInstance().singularize("companies"); // You'll get "company".
Inflector.getInstance().singularize("people"); // You'll get "person".
Inflector.getInstance().singularize("fish"); // You'll get "fish".